【问题标题】:Saving arraylist as SharedPreferences将 arraylist 保存为 SharedPreferences
【发布时间】:2015-07-07 06:55:04
【问题描述】:

我有一个包含许多元素的回收视图,我想在我的应用关闭和重新打开时使用 SharedPreferences 保存这些元素。我的数组的代码如下。

public ArrayList<MyInformation> getDataSet() {
        ArrayList results = new ArrayList<MyInformation>();    
        return results;
    }

(我在 myAdapter 中使用这个将东西添加到 recyclerview)

public void addEntity(int i, MyInformation entity) {
        information.add(i, entity);
        notifyItemInserted(i);
    }

那么,当我关闭应用程序时,我将如何保存这个数组? 谢谢!

【问题讨论】:

  • 你问的问题是什么?还要尽量确保你的英语是正确的,这真的很难阅读
  • @MathieuBrouwers 如何在我的回收站视图中保存元素
  • 对不起。我发这个的时候很着急。只要问我,我会很高兴地解决它。 :D
  • 你是怎么做到的?你成功了吗?如果是,请发布解决方案作为答案。谢谢

标签: android android-recyclerview sharedpreferences


【解决方案1】:

您可以使用 Gson 将 sharedpreferences 中的数据列表保存为字符串。 当然,在这样做之前,您需要添加必要的依赖项

dependencies {
    compile 'com.google.code.gson:gson:2.3.1'
}

然后当你想保存时,将你的数组转换成字符串:

ArrayList<MyInformation> yourData = new ArrayList<MyInformation>();
String dataStr = new Gson().toJson(yourData);

检索并转换回对象也很简单:

String str = "";//you need to retrieve this string from shared preferences.

Type type = new TypeToken<ArrayList<MyInformation>>() { }.getType();
ArrayList<MyInformation> restoreData = new Gson().fromJson(str, type);

给你了

【讨论】:

  • 谢谢!我现在就试试,然后向你汇报。
猜你喜欢
  • 2011-10-26
  • 2016-03-14
  • 2020-02-16
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2015-02-13
相关资源
最近更新 更多