【发布时间】:2019-07-10 00:51:03
【问题描述】:
我正在尝试为我正在使用 android 工作室制作的应用程序存储一个自定义对象数组列表。每当用户按下按钮时,我都需要能够将新对象添加到列表中。我的方法是首先使用正确的类型(try/catch 的捕获)初始化数组列表的空序列化版本。然后将该数组反序列化为名为“RecoTrackGameCollection”的临时数组列表,然后添加新对象,重新序列化数组并保存。
我遇到的问题是,当我尝试将任何对象添加到“RecoTrackGameCollection”时,代码会失败并运行 catch。
感谢您抽出宝贵时间查看此内容。如果您需要更多信息,请告诉我。
try {
//get shared pref
SharedPreferences prefs = mContext.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);
//deserilize
Gson gson = new Gson();
String serialRecoverList = prefs.getString("SavedGames", "");
Log.wtf("String Recover", serialRecoverList);
Type type = new TypeToken<List<Game>>(){}.getType();
ArrayList<Game> RecoTrackGameCollection = gson.fromJson(serialRecoverList, type);
//add game
RecoTrackGameCollection.add(SearchGameCollection.get(position));
//reserilize
Gson NewGson = new Gson();
String JsonTrakingGames = NewGson.toJson(RecoTrackGameCollection);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Games", JsonTrakingGames);
editor.commit();
Toast.makeText(mContext , "Game Saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Gson gson = new Gson();
String JsonTrakingGames = gson.toJson(TrackGameCollection);
SharedPreferences prefs = mContext.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Games", JsonTrakingGames);
editor.commit();
Toast.makeText(mContext , "iniatlizing", Toast.LENGTH_LONG).show();
}
这是游戏类
public class Game {
String name;
double price;
String link;
//constructor
Game(String name, double price,String link){
this.name = name;
this.price = price;
this.link = link;
}
}
我相信我的错误在于数组的反序列化。特别是这一行:
ArrayList<Game> RecoTrackGameCollection = gson.fromJson(serialRecoverList,
type);
【问题讨论】:
-
请阅读“如何创建minimal reproducible example”。然后使用edit 链接改进您的问题(不要通过 cmets 添加更多信息)。否则我们无法回答您的问题并为您提供帮助。如:什么是异常堆栈跟踪?并提示:了解类型擦除。那个空列表不知道它应该包含哪种类型的对象!
-
@GhostCat 会的,谢谢
-
再次:请阅读minimal reproducible example。你得到什么异常?添加堆栈跟踪!
-
@GhostCat 我有解决方案,所以我不会编辑这个问题,但下次一定要做好。感谢您的努力。
标签: java android arraylist gson sharedpreferences