我正在尝试为我正在使用 android studios 制作的应用程序存储对象的自定义数组列表。每当用户按下按钮时,我都需要能够将新对象添加到列表中。我的方法是首先使用正确的类型(try/catch 的捕获)初始化数组列表的空序列化版本。然后将该数组反序列化为名为“RecoTrackGameCollection”的临时数组列表,然后添加新对象,并重新序列化数组并保存它。
我遇到的问题是,当我尝试将任何对象添加到“RecoTrackGameCollection”时,代码会失败并运行捕获。
感谢您花时间看这个。如果您需要更多信息,请告诉我。
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);
一只斗牛犬
相关分类