【发布时间】:2014-09-12 10:28:41
【问题描述】:
我想为共享首选项保存一个布尔值。然后我将布尔值转换为字符串并填充文本视图。这段代码可以正常工作。但是如果我从模拟器中删除应用程序,布尔值就会丢失。所以我想知道,如果这是我保存布尔值的正确方法。
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;
}
}
感谢您的帮助!
这是将布尔值保存到 sharedpreferences 的正确方法吗?
如果我重新安装应用程序,我的数据丢失是否正确?
-
我不明白这一行:
boolean enabled = prefs.getBoolean("key", false);
为什么会有假?当我保存到共享首选项时,它会自动更改吗?
【问题讨论】:
-
SharedPreferences 仅对您的应用程序在“沙盒”上运行。当您删除/删除应用程序时,此沙箱中保存的所有数据也会被删除。
-
谢谢,如果我上传更新会怎样?更新安全吗?
-
是的。更新您的应用程序没问题。
标签: android boolean sharedpreferences