Reputation: 17
I'm trying to save the checked state of selected items of my recyclerView in the onPause()
method and restore in onResume()
,but the code in onResume()
causes my app to crash.
What am I doing wrong?
@Override
public void onPause() {
super.onPause();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(selectedList);
editor.putString("selected", json);
editor.commit();
}
@Override
public void onResume() {
super.onResume();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Gson gson = new Gson();
String json = sharedPrefs.getString("selected", "");
Type type = new TypeToken<ArrayList<ImageModel>>() {}.getType();
selectedList = gson.fromJson(json, type);
for (int i = 0; i < selectedList.size(); i++){
selectedList.get(i).setSelected(true);
}
if(selectedList == null){
selectedList = new ArrayList<>();
}
}
Upvotes: 0
Views: 89
Reputation: 66
First, you need to fix your code, you have on this line: for (int i = 0; i < selectedList.size(); i++)
an exception may be thrown java.lang.NullPointerException
. Alternatively, you can fix this and other problems in the following way:
@Override
public void onPause() {
super.onPause();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(selectedList);
editor.putString("selected", json);
editor.commit();
}
@Override
public void onResume() {
super.onResume();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String json = sharedPrefs.getString("selected", "");
if (json.isEmpty()) {
selectedList = new ArrayList<>();
} else {
fillSelectedList(json)
}
}
private void fillSelectedList(String json) {
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ImageModel>>() {}.getType();
selectedList = gson.fromJson(json, type);
if(selectedList == null){
selectedList = new ArrayList<>();
}
for (int i = 0; i < selectedList.size(); i++){
selectedList.get(i).setSelected(true);
}
}
Upvotes: 0