【发布时间】:2016-11-29 00:12:32
【问题描述】:
我正在学习 android,对于这个项目,我需要保存用户的数据 - 按钮的颜色变化,在这种情况下 -。在程序期间发生更改(onClick),但是当我重新启动应用程序时,没有任何反应 - 更改尚未保存(或读取......)有人可以帮助我吗?代码:
final String paintKey = "paint";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreate();
preferences();
togglePlay();
}
public void preferences(){ //the issue in this method?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
settings.getBoolean(paintKey,false);
String backGround = settings.getString("stage", "Indoors");
if (backGround.equals("Indoors")) {
Picasso.with(this).load(R.drawable.shocked_crowd).fit().centerCrop().into(stage);
}
if (backGround.equals("Street")) {
Picasso.with(this).load(R.drawable.coins).fit().centerCrop().into(stage);
}
}
public void changeColor(){
if(!paint) { //paint variable has global scope and it is set to false
c1.setBackgroundColor(Color.YELLOW);
paint = true;
}else{
c1.setBackgroundColor(Color.BLUE);
paint = false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("paint", paint);
editor.commit();
}
编辑:onClick 方法:
public void onClick(View v) {
if(v==color){
changeColor();
}
编辑:这就是我现在的样子:
public void preferences(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
final String paintKey = "paint";
settings.getBoolean(paintKey,false);
错了?如果我放置编辑器而不是设置,我会得到红色下划线
【问题讨论】:
-
我没有看到从“paint”键读取的代码:
settings.getBoolean("paint", false)。您应该阅读您保存到的相同密钥。理想情况下创建一个final String paintKey = "paint"变量。 -
我已经添加了该行,但它没有工作......也是最后的字符串
-
请相应更新问题和实际行为
-
我已经按照您的说法更新了代码,但仍然无法正常工作,当我退出应用程序时,按钮保持初始状态(白色)
-
很抱歉,我仍然看不到从 paintKey 设置中读取。此外,现在您应该像这样保存它:
editor.putBoolean(paintKey, paint);
标签: android sharedpreferences data-storage