Is it ok to save a JSON array in SharedPreferences?

前端 未结 9 2166
不知归路
不知归路 2020-11-28 08:29

I have a JSON Array that I need to save. I was thinking about serializing it, but would it be better to just save it as a string in SharedPreferences and then rebuild it whe

9条回答
  •  感动是毒
    2020-11-28 09:25

    Another Easy Way To Save JsonArray Into Sharedprefrences :

      public void SaveFriendList(String key, JSONArray value) {
    
        FriendLst = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = FriendLst.edit();
        editor.putString(key, value.toString());
        editor.commit();
    }
    
    
    
    public String LoadFriendList() {
        MyApplication.FriendLst = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String FriendLsts = MyApplication.FriendLst.getString("Friends", "");
        return FriendLsts;
    }
    

    Just Call this Code to get Your Json :-)

     try {
               JSONArray jarry1 = new JSONArray(LoadFriendList());
               JSONObject jobject;
                datamodelfriends.clear();
                 for (int i = 0; i < jarry1.length(); i++) {
                     jobject = jarry1.getJSONObject(i);
                     String FirstName = jobject.get("FirstName").toString();//You can get your own objects like this
                     datamodelfriends.add(new DataModelFriends(FirstName,...));
    
        }
        mAdapter = new CustomeAdapterFriendList(datamodelfriends, MainActivity.this);
    
                                    RecyclerView_Friends.setAdapter(mAdapter);
    
                                } catch (Exception e) {
                                }
    

提交回复
热议问题