[英]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.