I'm trying to put an ArrayList of self-created objects in SharedPreferences. While the saving seems to work, I get the following error when getSharedPreferences() is called:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.google.gson.Gson.fromJson(java.lang.String, java.lang.reflect.Type)' on a null object reference
The code where I put it into SharedPreferences:
// FYI: gson = new Gson(); is set earlier on
// same goes for: ArrayList<MovieModel> movieModelList = new ArrayList<>();
// and: Type listType;
movieModelList.add(result);
String jsonMovieModelList = gson.toJson(movieModelList);
SharedPreferences prefs = getSharedPreferences("settings",
MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("jsonMovieModelList", jsonMovieModelList);
editor.apply();
And the SharedPreferences class:
public void getSharedPreferences() {
SharedPreferences prefs = getSharedPreferences("settings",
MODE_PRIVATE);
String jsonMovieModelList = prefs.getString("jsonMovieModelList", null);
Log.d("TAG", "Message" + jsonMovieModelList); // output is as expected
// if not filled in, no action necessary
if (jsonMovieModelList != null) {
listType = new TypeToken<ArrayList<MovieModel>>(){}.getType();
ArrayList<MovieModel> movieModelListSaved = gson.fromJson(jsonMovieModelList, listType);
MovieModel lastMovie = movieModelListSaved.get(movieModelListSaved.size() - 1);
showTitleSecond = (TextView)findViewById(R.id.show_title_2);
showTitleSecond.setText(lastMovie.getTitle());
}
}
The gson code is based on: https://google.github.io/gson/apidocs/com/google/gson/Gson.html
To be clear: I do understand what a NullPointerException is, but I don't understand why I receive one in this situation since I check before executing that the String jsonMovieModelList is at least not null. Why is gson 'losing' the reference?
I look at this question: Android ArrayList of custom objects - Save to SharedPreferences - Serializable? and the only difference I see is that I have an ArrayList