Android List in SharedPreference

前端 未结 3 416
轮回少年
轮回少年 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:14

    The the following:

    Declare myList globally:

    ArrayList<String> myList = new ArrayList<String>();
    

    For setting value:

    for (int i = 0; i < totalSize; i++) {
        PreferenceManager.getDefaultSharedPreferences(this)
                         .edit()
                         .putString("number" + i, value + "").commit();         
    }
    

    For getting value:

    for (int i = 0; i < totalSize; i++) {
       myList.add(PreferenceManager.getDefaultSharedPreferences(this)
                                   .getString("number" + i, "0"));
    }
    

    NOTE:- totalSize is the size of your array

    0 讨论(0)
  • 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<List<String>>(){}.getType();
    
    Gson gson = new Gson();
    

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

    List<String> 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<String> 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.
    
    0 讨论(0)
  • 2021-01-23 05:24

    why do you using list ?(which is contains duplicate element)
    getting all element from sharedpreference

    Set<String> set = preference.getStringSet("key", null);
    
    //Set the values
    Set<String> set = new HashSet<String>();
    set.addAll(listOfExistingScores);
    preferenceEditor.putStringSet("key", set);
    preferenceEditor.commit();
    

    if you must use list check this link also https://gist.github.com/cr5315/6200903

    0 讨论(0)
提交回复
热议问题