[英]Android: issue with data storage (SharedPreferences)
我正在学习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);
错误? 如果我放置编辑器而不是设置,则带红色下划线
为了使用SharedPreferences
您需要一个全局密钥
final String paintKey = "paint"
编写布尔值信息SharedPreferences
使用
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(paintKey, paint).commit();
以后读取该数据
paint = settings.getBoolean(paintKey, false);
settings.getBoolean(paintKey,false);
该行从SharedPreferences中获取一个值,并立即将其忽略。 您必须将返回值保存在变量中,以便以后使用:
boolean paint = settings.getBoolean(paintKey,false);
这将创建只能在相同方法中使用的局部变量。 如果需要在其他方法中使用该值,请创建一个字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.