【问题标题】:How to save List<Object> to SharedPreferences?如何将 List<Object> 保存到 SharedPreferences?
【发布时间】:2015-03-22 08:36:48
【问题描述】:

我有一个产品列表,我从 web 服务检索,当应用程序第一次打开时,应用程序从 web 服务获取产品列表。我想将此列表保存到共享首选项中。

    List<Product> medicineList = new ArrayList<Product>();

产品类在哪里:

public class Product {
    public final String productName;
    public final String price;
    public final String content;
    public final String imageUrl;

    public Product(String productName, String price, String content, String imageUrl) {
        this.productName = productName;
        this.price = price;
        this.content = content;
        this.imageUrl = imageUrl;
    }
}

我如何保存这个列表而不是每次都从 web 服务请求?

【问题讨论】:

  • 您只能将原始值保存到 SharedPrefrences。

标签: java android sharedpreferences


【解决方案1】:

您目前有两个选择
a) 使用 SharedPreferences
b) 使用 SQLite 并在其中保存值。

如何执行
a) 共享偏好
首先将您的列表存储为一个集合,然后在您从 SharedPreferences 中读取时将其转换回一个列表。

Listtasks = new ArrayList<String>();
Set<String> tasksSet = new HashSet<String>(Listtasks);
PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("tasks_set", tasksSet)
    .commit();

然后当你阅读它时:

Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
    .getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);

b) SQLite 不错的教程:http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

【讨论】:

    【解决方案2】:

    在 SharedPreferences 中,您只能存储原语。

    一种可能的方法是您可以使用 GSON 并将值存储到 JSON 中的首选项中。

    Gson gson = new Gson();
    String json = gson.toJson(medicineList);
    
    yourPrefereces.putString("listOfProducts", json);
    yourPrefereces.commit();
    

    【讨论】:

      【解决方案3】:

      只能使用原始类型,因为偏好保留在内存中。但是您可以使用 Gson 将您的类型序列化为 json 并将字符串放入首选项中:

      private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
      
      private static SharedPreferences.Editor editor = sharedPreferences.edit();
          
      public <T> void setList(String key, List<T> list) {
          Gson gson = new Gson();
          String json = gson.toJson(list);
          
          set(key, json);
      }
      
      public static void set(String key, String value) {
          editor.putString(key, value);
          editor.commit();
      }
      

      @StevenTB 下方评论中的额外镜头

      检索

       public List<YourModel> getList(){
          List<YourModel> arrayItems;
          String serializedObject = sharedPreferences.getString(KEY_PREFS, null); 
          if (serializedObject != null) {
               Gson gson = new Gson();
               Type type = new TypeToken<List<YourModel>>(){}.getType();
               arrayItems = gson.fromJson(serializedObject, type);
           }
      }
      

      【讨论】:

      • 嘿,我知道这已经很晚了,但你为什么要使用静态变量和方法?
      • @albertkim 我相信这是因为他不需要每次需要 SharedPreferences 的新实例。他将一个变量藏在某个地方以备后用。
      • 你有没有用 GSON 存储后获取 List 的代码?
      • 要从序列化源中检索列表,请执行以下操作:List&lt;YourModel&gt; arrayItems; String serializedObject = sharedPreferences.getString(KEY_PREFS, null); if (serializedObject != null){ Gson gson = new Gson(); Type type = new TypeToken&lt;List&lt;YourModel&gt;&gt;(){}.getType(); arrayItems = gson.fromJson(serializedObject, type); }
      • 当您的实例是静态的时,您如何使用context.getShar...?我猜context 也是静态的,但是将上下文用作静态是否明智?
      【解决方案4】:

      您可以使用Gson 进行如下操作:

      • 从网络服务下载List&lt;Product&gt;
      • 使用new Gson().toJson(medicineList, new TypeToken&lt;List&lt;Product&gt;&gt;(){}.getType())List 转换为Json String
      • 像往常一样将转换后的字符串保存到SharePreferences

      为了重建您的List,您需要使用Gson 中提供的fromJson 方法恢复该过程。

      【讨论】:

        【解决方案5】:

        您可以使用 GSON 转换 Object -> JSON(.toJSON) 和 JSON -> Object(.fromJSON)。

        • 用你想要的定义你的标签(例如):

          private static final String PREFS_TAG = "SharedPrefs";
          private static final String PRODUCT_TAG = "MyProduct";
          
        • 获取这些标签的 sharedPreference

          private List<Product> getDataFromSharedPreferences(){
              Gson gson = new Gson();
              List<Product> productFromShared = new ArrayList<>();
              SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
              String jsonPreferences = sharedPref.getString(PRODUCT_TAG, "");    
          
              Type type = new TypeToken<List<Product>>() {}.getType();
              productFromShared = gson.fromJson(jsonPreferences, type);
          
              return preferences;
          }
          
        • 设置您的 sharedPreferences

          private void setDataFromSharedPreferences(Product curProduct){
              Gson gson = new Gson();
              String jsonCurProduct = gson.toJson(curProduct);
          
              SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
              SharedPreferences.Editor editor = sharedPref.edit();
          
              editor.putString(PRODUCT_TAG, jsonCurProduct);
              editor.commit();
          }
          
        • 如果您想保存一组产品,请执行以下操作:

          private void addInJSONArray(Product productToAdd){
          
              Gson gson = new Gson();
              SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
          
              String jsonSaved = sharedPref.getString(PRODUCT_TAG, "");
              String jsonNewproductToAdd = gson.toJson(productToAdd);
          
              JSONArray jsonArrayProduct= new JSONArray();
          
              try {
                  if(jsonSaved.length()!=0){
                      jsonArrayProduct = new JSONArray(jsonSaved);
                  }
                  jsonArrayProduct.put(new JSONObject(jsonNewproductToAdd));
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          
              //SAVE NEW ARRAY
              SharedPreferences.Editor editor = sharedPref.edit();
              editor.putString(PRODUCT_TAG, jsonArrayProduct);
              editor.commit();
          }
          

        【讨论】:

        • 从 JSONArray 中检索 Products 数组的代码是什么?
        • 当您尝试使用此行时,您不能将 json 直接放入 SharedPreference 中:editor.putString(PRODUCT_TAG, jsonArrayProduct); 您必须先将其转换为字符串(可能使用代码中的 Gson 对象)。例如:gson.toJson(jsonArrayProduct)
        • 我得到了 Expected BEGIN_ARRAY 但在获取对象时在第 1 行第 2 列路径 $ 处是 BEGIN_OBJECT
        【解决方案6】:

        所有与 JSON 相关的答案都可以,但请记住,如果您实现 java.io.Serializable 接口,Java 允许您序列化任何对象。 这样,您也可以将其作为序列化对象保存到首选项中。 以下是存储为首选项的示例:https://gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111 我希望这可以作为一种选择对您有所帮助。

        【讨论】:

          【解决方案7】:
          SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
          

          保存

          Editor prefsEditor = mPrefs.edit();
          Gson gson = new Gson();
          String json = gson.toJson(myObject);
          prefsEditor.putString("MyObject", json);
          prefsEditor.commit();
          

          为了得到

          Gson gson = new Gson();
          String json = mPrefs.getString("MyObject", "");
          MyObject obj = gson.fromJson(json, MyObject.class);
          

          【讨论】:

          • 问题已经回答并接受,为什么要添加重复的答案?
          【解决方案8】:

          正如在接受的答案中所说,我们可以保存对象列表,例如:

          public <T> void setList(String key, List<T> list) {
                  Gson gson = new Gson();
                  String json = gson.toJson(list);
                  set(key, json);
              }
          
              public void set(String key, String value) {
                  if (setSharedPreferences != null) {
                      SharedPreferences.Editor prefsEditor = setSharedPreferences.edit();
                      prefsEditor.putString(key, value);
                      prefsEditor.commit();
                  }
              }
          

          通过以下方式获取:

          public List<Company> getCompaniesList(String key) {
              if (setSharedPreferences != null) {
          
                  Gson gson = new Gson();
                  List<Company> companyList;
          
                  String string = setSharedPreferences.getString(key, null);
                  Type type = new TypeToken<List<Company>>() {
                  }.getType();
                  companyList = gson.fromJson(string, type);
                  return companyList;
              }
              return null;
          }
          

          【讨论】:

            【解决方案9】:

            对我来说最好的解决方案,我认为你:

            private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
            private  SharedPreferences.Editor editor = sharedPreferences.edit();
            List<your object> list = new ArrayList<>();
            

            保存:

            editor.edit().putString("your key name", new Gson().toJson(list)).apply();
            

            获取:

            list = new Gson().fromJson(sharedPreferences.getString("your key name", null), new TypeToken<List<your object class name>>(){}.getType());
            

            尽情享受吧!

            【讨论】:

              【解决方案10】:

              首先您需要创建函数来将数组列表保存到 SharedPreferences。

              public void saveListInLocal(ArrayList<ModelName> list, String key) {
              SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
              SharedPreferences.Editor editor = prefs.edit();
              Gson gson = new Gson();
              String json = gson.toJson(list);
              editor.putString(key, json);
              editor.apply();   }
              

              您需要创建函数来从 SharedPreferences 中获取数组列表。

              public ArrayList<ModelName> getListFromLocal(String key)
              {
              SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
              Gson gson = new Gson();
              String json = prefs.getString(key, null);
              Type type = new TypeToken<ArrayList<ModelName>>() {}.getType();
              return gson.fromJson(json, type);
              
              }
              

              如何调用保存和检索数组列表函数。

               ArrayList<ModelName> listSave=new ArrayList<>();
               listSave.add("test1"));
               listSave.add("test2"));
               saveListInLocal(listSave,"key");
               Log.e("saveArrayList:","Save ArrayList success");
               ArrayList<ModelName> listGet=new ArrayList<>();
               listGet=getListFromLocal("key");
               Log.e("getArrayList:","Get ArrayList size"+listGet.size());
              

              【讨论】:

                【解决方案11】:

                在 Kotlin 中获取通用列表的完美功能

                private fun <T : Serializable> getGenericList(
                    sharedPreferences: SharedPreferences,
                    key: String,
                    clazz: KClass<T>
                ): List<T> {
                    return sharedPreferences.let { prefs ->
                        val data = prefs.getString(key, null)
                        val type: Type = TypeToken.getParameterized(MutableList::class.java, clazz.java).type
                        gson.fromJson(data, type) as MutableList<T>
                    }
                }
                

                你可以调用这个函数

                getGenericList.(sharedPrefObj, sharedpref_key, GenericClass::class)
                

                【讨论】:

                  猜你喜欢
                  • 2020-08-02
                  • 2021-10-21
                  • 1970-01-01
                  • 2019-10-05
                  • 2022-09-27
                  • 1970-01-01
                  • 2021-10-11
                  • 1970-01-01
                  • 2021-11-23
                  相关资源
                  最近更新 更多