因此,我尝试向SharedPreferences
中添加一些值,但是每次单击按钮时,它都与默认值00
一起使用,因此即使if语句不应该,其if语句也始终返回true t。
private static final String SHARED_FREFS = "sharedPrefs";
private static final String STATE = "state";
这是按钮单击事件
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_FREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
int currentTime = Calendar.getInstance().getTime().getMinutes();
String eh = sharedPreferences.getString(STATE, "00");
if(!Integer.toString(currentTime).equalsIgnoreCase(sharedPreferences.getString(STATE, "00"))){
GetData();
editor.putString(STATE, Integer.toString(currentTime));
Log.e("ATTENTION!:", "METHOD HAS BEEN FIRED!");
}
}
});
我正在尝试将当前分钟存储在其中,但没有这样做。
我是否需要一个名为data的文件夹,其中包含一个名为sharedPrefs
的xml文件?
答案 0 :(得分:5)
为什么单击按钮后我的SharedPreferences不保存?
因为您忘记了将更新保存在SharedPreferences
在editor.apply();
editor.commit();
或 SharedPreferences
示例
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_FREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
int currentTime = Calendar.getInstance().getTime().getMinutes();
String eh = sharedPreferences.getString(STATE, "00");
if(!Integer.toString(currentTime).equalsIgnoreCase(sharedPreferences.getString(STATE, "00"))){
GetData();
editor.putString(STATE, Integer.toString(currentTime));
editor.apply();
Log.e("ATTENTION!:", "METHOD HAS BEEN FIRED!");
}
}
});
答案 1 :(得分:3)
答案 2 :(得分:3)
正如我所看到的那样,在共享首选项编辑器中添加数据后,总是需要使用editor.commit()
或editor.apply()
。应该使用哪一个,请参见下文:
apply() vs commit();
commit(): this method runs synchronously means,
1. thread safe.
2. slow.
and always gives feed back but
apply(): this method runs asynchronously means.
1. no thread safe.
2. runs fast.
and does not give feedback.
Finally sharedPreferences instances are singleton with in a process it's safe to replace any instance of commit() with apply(), if you were already ignoring the return value.
根据您的要求使用。