Android Studio SharedPreferences - 如何保存布尔值?

时间:2017-08-08 19:22:07

标签: java android boolean sharedpreferences

我想知道如何使用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

2 个答案:

答案 0 :(得分:1)

您未检查条件以启用或禁用您从SharedPreference获取的按钮。做这样的事情:

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

答案 1 :(得分: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(); 

像这样存储值

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

获得这样的价值

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