这是在sharedpreferences中保存布尔值的正确方法吗?

时间:2014-09-12 10:28:41

标签: android boolean sharedpreferences

我想将一个布尔值保存到共享首选项。然后我将布尔值转换为字符串并填充textview。它可以正常使用此代码。但是,如果我从模拟器中删除应用程序,则布尔值将丢失。所以我想知道,如果我保存布尔值是正确的方法。

public class MainActivity extends Activity implements OnClickListener {
public TextView bool;
public boolean enabled;
public Button button;

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

         SharedPreferences prefs = this.getSharedPreferences(
                  "com.example.app", Context.MODE_PRIVATE);
        boolean enabled = prefs.getBoolean("key", false);

        TextView bool = (TextView) findViewById(R.id.bool);
        String theValueAsString = new Boolean(enabled).toString();
        bool.setText(theValueAsString);

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

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        changeBoolean();
         SharedPreferences prefs = this.getSharedPreferences(
                  "com.example.app", Context.MODE_PRIVATE);
        boolean enabled = prefs.getBoolean("key", false);
        TextView bool = (TextView) findViewById(R.id.bool);
        String theValueAsString = new Boolean(enabled).toString();
        bool.setText(theValueAsString);

    }

    public boolean changeBoolean(){
         SharedPreferences prefs = this.getSharedPreferences(
                  "com.example.app", Context.MODE_PRIVATE);
        enabled =  true;
        prefs.edit().putBoolean("key",enabled).commit();
        return enabled;

    }

}

感谢您的帮助!

  1. 这是将布尔值保存到共享偏好的正确方法吗?

  2. 是否正确,如果我重新安装应用程序,我的数据会丢失?

  3. 我不知道这句话:

    boolean enabled = prefs.getBoolean(" key",false);

  4. 为什么有假?当我保存到共享偏好时,它会自动更改吗?

2 个答案:

答案 0 :(得分:1)

  

这是将布尔值保存到共享偏好的正确方法吗?

如果您希望changeBoolean()始终保存值true而不是"更改"价值。

  

是否正确,如果我重新安装应用程序,我的数据会丢失?

重新安装会保留您的应用数据。只有当您卸载或明确选择清除应用程序的数据时,共享首选项也会丢失。

  

我不知道这句话:

boolean enabled = prefs.getBoolean("key", false);
     

为什么有假?当我保存到共享偏好时,它会自动更改吗?

第二个参数是默认值。如果共享首选项中getBoolean()没有保存值,则会"key"返回。

答案 1 :(得分:0)

您可以使用以下代码设置布尔值

    SharedPreferences.Editor editor = context.getSharedPreferences(you_pref_name, Context.MODE_PRIVATE).edit();
    editor.putBoolean(YOUR_KEY, you_boolean_value);
    editor.commit();

获取布尔值:

SharedPreferences preferences = context.getSharedPreferences(you_pref_name, Context.MODE_PRIVATE);
        return preferences.getBoolean(YOUR_KEY, false);
相关问题