2017-08-08 133 views
-1

我想知道如何使用SharedPreferences存储布尔值并禁用按钮。如果您重新启动应用程序,该按钮应保持禁用状态。 这是我的代码,但有些地方是错误的。Android Studio SharedPreferences - 如何保存布尔值?

public class Pass extends AppCompatActivity implements View.OnClickListener { 

private Button btn1; 
private EditText text1; 

private SharedPreferences speicher; 
private SharedPreferences.Editor editor; 

final boolean enabled = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_pass); 

    btn1 = (Button) findViewById(R.id.button); 
    btn1.setOnClickListener(this); 

    text1 = (EditText) findViewById(R.id.editText); 
    text1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); 

    speicher = getApplicationContext().getSharedPreferences("Daten", 0); 
    editor = speicher.edit(); 

    speicher = getSharedPreferences("Daten", 0); 
    speicher.getBoolean("Data1", enabled); 

} 


public void onClick (View view){ 


    if (text1.getText().toString().equals("pass")){ 
     AlertDialog ad = new AlertDialog.Builder(this).create(); 
     ad.setMessage("Great"); 
     ad.show(); 
     Intent intent = new Intent(this,Popup.class); 
     startActivity(intent); 

     btn1.setEnabled(enabled); 

     editor.putBoolean("Data1", enabled); 
     editor.commit(); 

    }else{ 
     String message = "Wrong"; 
     Toast.makeText(this,message, Toast.LENGTH_LONG).show(); 
    } 
} 

} 

我希望你能帮助我。

因为

Strecki

+1

的可能重复这个

editor.putBoolean("Data1", true); editor.commit(); 

获得价值值[如何存储在Android中使用SharedPreferences的布尔值?](https:// stackov erlang.com/questions/23919338/how-to-store-a-boolean-value-using-sharedpreferences-in-android) – Ibrahim

+0

您已经保存了布尔值。你想知道如何检索它吗? –

+0

可能的重复https://stackoverflow.com/questions/4967418/using-shared-preferences-editor – Stuckzilla

回答

1

你不检查的情况下使能或你是从SharedPreference越来越禁用按钮。做这样的事情:

btn1.setEnabled(speicher.getBoolean("Data1", enabled)); 
+0

@威尔谢谢! –

0

试试这个它会工作。

Remove this line on your code. Because initialized again here. 

"speicher = getSharedPreferences("Daten", 0);" 

你一定要试试这样

SharedPreferences speicher = getApplicationContext().getSharedPreferences("Daten", 0); 
SharedPreferences.Editor editor = speicher.edit(); 

商店喜欢这样

Boolean result = speicher.getBoolean("Data1", false); //false is default value.