Is it possible to add an array or object to SharedPreferences on Android

前端 未结 11 1733
别跟我提以往
别跟我提以往 2020-11-22 11:27

I have an ArrayList of objects that have a name and an icon pointer and I want to save it in SharedPreferences. How can I do?

NOTE:

11条回答
  •  轮回少年
    2020-11-22 11:46

    You can use putStringSet

    This allow you to save a HashSet in your preferences, just like this:

    Save

    Set values;
    
    SharedPreferences sharedPref = 
        mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
    
    Editor editor = sharedPref.edit();
    
    editor.putStringSet("YOUR_KEY", values);
    editor.apply();
    

    Retrive

    SharedPreferences sharedPref = 
        mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
    
    Editor editor = sharedPref.edit();
    
    Set newList = editor.getStringSet("YOUR_KEY", null);
    

    The putStringSet allow just a Set and this is an unordered list.

提交回复
热议问题