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);
}
}
添加回答
举报
