1 回答

TA貢獻1784條經驗 獲得超2個贊
那是因為您在保存和獲取列表時使用了不同的密鑰。
您可以使用以下方法保存列表:
private void saveGames(Lis<Game> games) {
Gson gson = new Gson();
String json = gson.toJson(games);
SharedPreferences prefs = ctx.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Games", json);
editor.commit();
}
以及以下獲取列表:
private List<Game> getGames(Context ctx) {
Gson gson = new Gson();
SharedPreferences prefs = ctx.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);
String json = prefs.getString("Games", "");
if(json.isEmpty()) {
return new ArrayList<>();
} else {
Type type = new TypeToken<List<Game>>(){}.getType();
return gson.fromJson(json, type);
}
}
添加回答
舉報