【问题标题】:Android Studio SharedPreferences - How I can save boolean?Android Studio SharedPreferences - 我如何保存布尔值?
【发布时间】:2017-08-08 19:22:07
【问题描述】:

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

}

希望你能帮助我。

因为

斯特雷奇

【问题讨论】:

  • 您已经在保存布尔值。你想知道如何找回它吗?
  • 您需要在 onResume() 方法中执行此操作:((Button) findViewById(R.id.button)).setEnabled(speicher.getBoolean("Data1", enabled));跨度>
  • 嗨,我知道你是新来的。如果您认为某个答案解决了问题,请单击绿色复选标记将其标记为“已接受”。这有助于将注意力集中在仍然没有答案的旧 SO。

标签: java android boolean sharedpreferences


【解决方案1】:

您没有检查从SharedPreference 获得的启用或禁用按钮的条件。做这样的事情:

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

【讨论】:

    【解决方案2】:

    试试这个就行了。

    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-18
      • 2020-08-02
      • 2019-11-25
      • 2020-02-25
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多