Android List in SharedPreference

前端 未结 3 415
轮回少年
轮回少年 2021-01-23 05:06

I am trying to edit values from List in SharedPreferences but someting is going wrong.

My SharedPreference is:

public class StepsData {
    static Shared         


        
3条回答
  •  余生分开走
    2021-01-23 05:19

    if you want to store List object in SharedPreference then use gson library. It will use to convert list object into json format and store that json string into sharedPref.
    First include this line in gradle file(app level)

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

    below code is to set the Type to List

    Type listType = new TypeToken>(){}.getType();
    
    Gson gson = new Gson();
    

    Now Create list object and convert to json string format using gson object and type

    List myList = new ArrayList<>();
    //add elements in myList object
    
    String jsonFormat = gson.toJson(myList,listType);  
    //adding to sharedPref  
    editor.put("list",jsonFormat).apply();
    

    Now get the values from sharedPref and convert json string back to List object.

    //this line will get the json string from sharedPref and will converted into object of type list(specified in listType object) 
    List list = gson.fromJson(sharedPref.get("list",""),listType);  
    //now modify the list object as par your requirement and again do the same step of converting that list object into jsonFormat.
    

提交回复
热议问题