为了账号安全,请及时绑定邮箱和手机立即绑定

反序列化自定义对象的序列化 ArrayList,添加对象,然后重新序列化

反序列化自定义对象的序列化 ArrayList,添加对象,然后重新序列化

慕容森 2022-06-23 16:22:02
我正在尝试为我正在使用 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);
查看完整描述

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);

  }


}


查看完整回答
反对 回复 2022-06-23
  • 1 回答
  • 0 关注
  • 145 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号