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

问题描述:

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

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. 这是保存布尔值为sharedpreferences的正确方法吗?

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

  3. 我不unterstand这一行:

    布尔启用= prefs.getBoolean( “键”,假);

为什么会出现错误?当我保存到sharedpreferences时它会自动更改吗?

+0

SharedPreferences仅在您的应用程序上运行“SandBox”。当您删除/删除应用程序时,该沙盒中保存的所有数据也会被删除。 – 2014-09-12 10:39:26

+0

谢谢,如果我上传更新会发生什么?更新是否安全? – basti12354 2014-09-12 10:40:27

+0

是的。更新应用程序没有问题。 – 2014-09-12 10:41:50

这是保存一个布尔值sharedpreferences正确的方式?

这是有效的,如果你打算changeBoolean()总是保存价值true而不是“改变”的价值。

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

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

我不unterstand这一行:

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

为什么有假?当我保存到sharedpreferences时它会自动更改吗?

第二个参数是默认值。 getBoolean()在共享首选项中没有为"key"保存值的情况下返回它。

您可以使用下面的代码来设置布尔

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);