【问题标题】:how to store ArrayList<HashMap<String, String>> data into sharedpreferences?如何将 ArrayList<HashMap<String, String>> 数据存储到 sharedpreferences 中?
【发布时间】:2016-02-20 13:26:07
【问题描述】:

我有一个“ArrayList> List_Data =new ArrayList>();”

但我的要求是将 List_Data 存储到 sharedpreference 中。请帮帮我。

【问题讨论】:

标签: android


【解决方案1】:

将您的数组或对象转换为 JSON 并存储到共享首选项中

用于存储:

SharedPreferences db=PreferenceManager.getDefaultSharedPreferences(context);

Editor collection = db.edit();
Gson gson = new Gson();
String arrayList1 = gson.toJson(arrayList);

collection.putString(key, arrayList1);
collection.commit();

用于检索

SharedPreferences db=PreferenceManager.getDefaultSharedPreferences(context);

Gson gson = new Gson();
String arrayListString = db.getString(key, null);  
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(arrayListString, type);

【讨论】:

    【解决方案2】:

    使用 Gson 或任何其他方法将您的对象序列化为 json 字符串,然后将此字符串存储在 SP 中。要获取此对象:获取字符串并将其反序列化为您的数组。

    【讨论】:

      【解决方案3】:

      仅当您想要保存的键值集合相对较少时,才尝试使用共享首选项

      以下是如何将列表保存到共享偏好中

      使用 gson 或您选择的任何其他库对其进行序列化

      Gson gson = new Gson();
      String serializedMapData = gson.toJson(mapList);
      preferenceObj.edit().putString("key", mapList)
      

      再次使用 gson 将其转换回对象

      String mapListString= preferenceObj.getString("key");
      List<Map<String, String>> map = gson.fromJson(string, List.class);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-18
        • 1970-01-01
        • 2016-05-07
        • 2013-05-07
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多