在共享首选项android中保存模型类的ArrayList<ModelClass>

Posted

技术标签:

【中文标题】在共享首选项android中保存模型类的ArrayList<ModelClass>【英文标题】:Save ArrayList<ModelClass> of model class in shared preference android 【发布时间】:2021-11-05 07:31:00 【问题描述】:

我正在使用 API 并将其响应保存在共享偏好中。我在共享首选项中保存列表时出错

API 响应:

club": 
    "username": "ADMIN",
    "email": "admin@gmail.com",
  ,
  "channel": 
    "id": "QiExQlHA23rknooEYOVB",
    "previewTime": "158",
    "playlist": [
      
        "playlist_id": "nJRYT001IEYb5Oj1eWiw",
      
    ],
    "name": "donottouchit"
  ,
  "**playlist**": [
    
      "id": "nJRYT001IEYb5Oj1eWiw",
      "media": [
        
          "name": "Doe Het Zelf zwemba.m4",
          "type": "video/mp4",
          "thumbnailPath": "mediafiles/2oHU5H3Pw62BgS8jNbl2/1628674169481_2oHU5H3Pw62BgS8jNbl2_thumbnail.jpeg",
          "url": "https://firebasestorage.googleapis.com/v0/b/dev-expo-sports.appspot.com/o/mediafiles%2F2oHU5H3Pw62BgS8jNbl2%2F1628674171950_Doe%20Het%20Zelf%20zwembad.mp4?alt=media&token=49742805-206b-46ab-b4e2-fca5ada4236b",
          "height": 1080,
          "width": 1920,
          "thumbnailURL": "https://firebasestorage.googleapis.com/v0/b/dev-expo-sports.appspot.com/o/mediafiles%2F2oHU5H3Pw62BgS8jNbl2%2F1628674169481_2oHU5H3Pw62BgS8jNbl2_thumbnail.jpeg?alt=media&token=9811078e-552e-424c-bceb-d10fe80045d8",
          "id": "AM8QE71IQ9sl3sXDA1TL",
          "duration": "37.719333"
        ,
        
          "name": "halee-burgess-mainphpAE8.jpeg",
          "url": "https://firebasestorage.googleapis.com/v0/b/dev-expo-sports.appspot.com/o/mediafiles%2FmX935y8INTI7A855VhxI%2F1630907577000_halee-burgess-mainphpAE8.jpeg?alt=media&token=496a62af-e200-426a-9c5f-0d161973269d",
          "id": "2NWBltMh2q1wdUaqEUuX",
          "height": 1024,
          "type": "image/jpeg",
          "width": 1024,
          "duration": "10"
        ,
      
      ],
    
  ],

这里我有俱乐部和频道,但在 PlayList 作为其返回列表时遇到问题。

这就是我得到它的响应以及它在列表中获取正确数据的方式。我已经打印了数据

JSONArray jsonArray = response.getJSONArray("playlist");
List<PlayListModel> list =   gson.fromJson(String.valueOf(jsonArray), new TypeToken<List<PlayListModel>>() .getType());

将其保存在共享首选项中的功能

String json = gson.toJson(list);
SharedPreferenceUtils.getInstance().saveString(context,"playlistMediaData", json);

public void saveString(Context context, String sharedPrefName, String value) 
        SharedPreferences  mPrefs = context.getSharedPreferences("MYPREFERENCES", Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(value);

        prefsEditor.putString(sharedPrefName, json);
        prefsEditor.commit();
    

我试图检索它的功能:

 ArrayList<PlayListModel> PlayList = SharedPreferenceUtils.getInstance().retrieveListJson(context,"playlistMediaData");

public ArrayList<PlayListModel> retrieveListJson(Context context, String sharedPrefName)
        ArrayList<PlayListModel> arrayItems = new ArrayList<>();
        SharedPreferences  mPrefs = context.getSharedPreferences("MYPREFERENCES", Context.MODE_PRIVATE);
        String serializedObject = mPrefs.getString(sharedPrefName, "");
         if (serializedObject != null) 
            Gson gson = new Gson();
            Type type = new TypeToken<List<PlayListModel>>().getType();
             return arrayItems = gson.fromJson(serializedObject, type);
        
         return  null;
    

/*    public Collection<PlayListModel> retrieveListJson(Context context, String sharedPrefName) 
        Type collectionType = new TypeToken<Collection<PlayListModel>>().getType();
        Gson gson = new Gson();
        SharedPreferences  mPrefs = context.getSharedPreferences("MYPREFERENCES", Context.MODE_PRIVATE);
        String json = mPrefs.getString(sharedPrefName, "");
        Collection<PlayListModel> enums = gson.fromJson(json, collectionType);
        return enums;
    */

除此之外,我尝试了多种方法,但每次都遇到相同的错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $
        at com.google.gson.Gson.fromJson(Gson.java:944)
        at com.google.gson.Gson.fromJson(Gson.java:897)
        at com.google.gson.Gson.fromJson(Gson.java:846)
        at com.solis.expo.apiCall.ApiCallService.retrieveData(ApiCallService.java:145)
        at com.solis.expo.apiCall.ApiCallService.access$000(ApiCallService.java:30)
        at com.solis.expo.apiCall.ApiCallService$1.onResponse(ApiCallService.java:79)
        at com.solis.expo.apiCall.ApiCallService$1.onResponse(ApiCallService.java:49)
        at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:100)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)

我不知道我做错了什么,但我无法理解这个问题并且已经尝试了几乎所有关于 *** 的解决方案 谢谢

【问题讨论】:

【参考方案1】:

在共享偏好中保存列表

 SharedPreferences  mPrefs = context.getSharedPreferences("MYPREFERENCES", Context.MODE_PRIVATE);
JSONArray playlist = response.getJSONArray("playlist");
mPrefs.edit().putString("playlist",playlist.toString()).apply();

然后检索您的列表:

PlayListModel[] playListModels=new Gson().fromJson(mPrefs.getString("playlist",""), PlayListModel[].class);
    Log.d("tag",playListModels.toString());

【讨论】:

以上是关于在共享首选项android中保存模型类的ArrayList<ModelClass>的主要内容,如果未能解决你的问题,请参考以下文章

如何以共享首选项保存图像?

如何使用android中的共享首选项将数据保存在editText中[重复]

在共享首选项中保存大型arraylists

Android - 保存自定义对象 - 共享首选项或数据库?

如何将 HashMap 保存到共享首选项?

Android 共享首选项分配不会在模拟器会话之间持续存在