【问题标题】:How to save an ArrayList <List>如何保存 ArrayList <List>
【发布时间】:2016-07-29 02:30:35
【问题描述】:

我有一个包含 ArrayList 的 ab ArrayList,它们再次包含列表。字符串之一和视图之一。我怎样才能将此根列表保存到共享首选项或其他任何地方?这是一个概述:

           MotherList
                | 
                .
          DaughterLists
            /       \
           /         \
    ListOfViews  ListOfStrings
                .
                .

【问题讨论】:

  • 这是一个安卓问题吗?
  • 为什么要将android.view.View 保存在SharedPreferences 中?我不明白这是什么意思。
  • 您为什么还要保留视图列表?这听起来像是一个 recyclerview 场景......
  • 可能是 thisthis 的副本?
  • 将对象转换为字符串并保存在共享首选项中

标签: java android arrays list sharedpreferences


【解决方案1】:

以下是关于将数据放入 SharedPreferences 的所有方法: putBoolean(字符串键,布尔值 v) putInt(字符串 k,int v) putFloat(字符串 k,float v) putLong(字符串 k,long v) putString(字符串 k,字符串 v) putStringSet(String k,Set v)

但是有一个叫ASimpleCache的开源框架可以解决它:

保存: ACache acache = ACache.get(Context); acache.put("key",your-root-list); 得到: acache.getAsObject("key");

【讨论】:

    【解决方案2】:

    您好,我建议您使用 GSON 来序列化和反序列化您的列表。通过这种方式,您可以轻松地将其保存到您的SharedPreferences

    1. 首先在 GSON Converter

      的帮助下将您的 ArrayList&lt;List&gt; 对象转换为 JSON
      String myArrayListAsJSON = new Gson().toJson(myArrayList); // you will pass your arraylist variable to toJson() method
      
    2. 将您的 JSON 对象保存为 String 在您的 SharedPreference

      SharedPreferences prefs=this.getSharedPreferences("PREF_KEY_FOR_YOUR_APP",Context.MODE_PRIVATE);
      Editor edit=prefs.edit();
      
      edit.putString("myListKey", myArrayListAsJSON); // we will put our list hat serialized with GSON here
      edit.commit();
      
    3. 在您申请的任何地点/时间重复使用您的列表。您只需要反序列化保存在 Shared Preferences 上的 JSON

      SharedPreferences prefs=this.getSharedPreferences("PREF_KEY_FOR_YOUR_APP",Context.MODE_PRIVATE);
      String myListAsString = prefs.getString("myListKey","default_value");
      ArrayList<List> yourObject = new Gson().fromJson(myListAsString, YOUR_MODEL.class);
      

    Gson 是一个 Java 库,可用于将 Java 对象转换为其 JSON 表示形式。它还可用于将 JSON 字符串转换为等效的 Java 对象。 Gson 可以处理任意 Java 对象,包括您没有源代码的预先存在的对象。

    您可以通过将此行添加到您的依赖项来在您的应用中使用 GSON

    compile 'com.google.code.gson:gson:2.6.2'
    

    您可以在GSON Github Page 上找到更多详细信息和示例

    【讨论】:

      【解决方案3】:

      使用共享首选项存储 Arraylist

      SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
      Editor edit=prefs.edit();
      
      Set<String> set = new HashSet<String>();
      set.addAll(your Arraylist Name);
      edit.putStringSet("yourKey", set);
      edit.commit();
      

      从共享首选项中检索 Arraylist

      Set<String> set = prefs.getStringSet("yourKey", null);
      List<String> sample=new ArrayList<String>(set);
      

      【讨论】:

      • 您可以将其转换为 JSON 字符串并将该字符串存储在共享首选项中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2014-05-17
      • 2014-06-26
      • 2023-03-14
      • 1970-01-01
      • 2018-08-05
      • 2013-10-04
      相关资源
      最近更新 更多