我試圖在SharedPreferences中放置自創對象的ArrayList。雖然儲蓄似乎工作,我得到的時候getSharedPreferences()被調用以下錯誤:Gson&SharedPreferences導致NullPointerException
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
,我把它放到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();
而且SharedPreferences類:
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());
}
}
的GSON代碼是基於:https://google.github.io/gson/apidocs/com/google/gson/Gson.html
要清楚: 我明白什麼是NullPointerException,但我不明白爲什麼我會在這種情況下收到一個,因爲我在執行之前檢查字符串jsonMovieModelList至少不爲null。爲什麼gson'失去'參考?
我看這個問題:Android ArrayList of custom objects - Save to SharedPreferences - Serializable?,我看到唯一的區別是,我有一個ArrayList
感謝您的期待,但是,正如我在註釋行中所述,我使用gson = new Gson()初始化gson。任何其他建議? – CorneeldH
Uhm,顯示整個代碼,也許變量範圍與此有關... – Vucko
閱讀您的評論並重新閱讀您的答案,您是對的!在getSharedPreferences中,我沒有初始化gson,並且在重新啓動應用程序之前加載此方法。所以,從我身邊道歉,並感謝您的答覆+評論:) – CorneeldH