我已经将所有代码保存在方法saveData()
中保存共享首选项,我想如果我将该方法放在生命周期结束的OS方法(onStop(),onDestroy())中它将是应用程序关闭时会自动调用,但事实并非如此!
如何实现这一目标?
public void saveData() {
mSharedPreferences = getSharedPreferences(KEY_SHARED_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mGson = new Gson();
String s1 = mGson.toJson(t); //ArrayList<CustomObj>
String s2 = mGson.toJson(g); //ArrayList<String>
String s3 = mGson.toJson(i); //CustomObj
mEditor.putString(KEY_T, s1);
mEditor.putString(KEY_G, s2);
mEditor.putString(KEY_I, s3);
mEditor.putString(KEY_SELECT, select);
mEditor.putInt(KEY_POSITION_T, positionT);
mEditor.putInt(KEY_POSITION_M, positionM);
mEditor.apply();
}
我在YouTube视频中看到了这一点,所以它不应该是一个问题,我不能把剩下的活动因为它太长了。
答案 0 :(得分:1)
我猜您认为数据未保存在SharedPreferences
中,因为您无法读取它们,因为它始终是null
。但是没有必要使SharedPreferences
成为一个类变量。试试这个并将saveData()
放在onStop()
方法中:
public void saveData() {
//No need to make the SharedPreferences object a class instance variable...keep it local
SharedPreferences sharedPreferences = getSharedPreferences(KEY_SHARED_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
mGson = new Gson();
String s1 = mGson.toJson(t); //ArrayList<CustomObj>
String s2 = mGson.toJson(g); //ArrayList<String>
String s3 = mGson.toJson(i); //CustomObj
editor.putString(KEY_T, s1);
editor.putString(KEY_G, s2);
editor.putString(KEY_I, s3);
editor.putString(KEY_SELECT, select);
editor.putInt(KEY_POSITION_T, positionT);
editor.putInt(KEY_POSITION_M, positionM);
editor.apply();
}
现在从loadData()
调用onCreate()
(您不检查mSharedPreferences是否为null
...甚至不要将其声明为类变量!!)
private void loadData() {
try {
SharedPreferences pref = getSharedPreferences(KEY_SHARED_PREFERENCES, MODE_PRIVATE);
//If the key is not available neither are the values!!
if(pref.contains(KEY_T)){
//read your data!!
}
}
catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}