Storing Array List Object in SharedPreferences

前端 未结 3 1289
孤街浪徒
孤街浪徒 2020-12-02 10:04

This method add new object into ArrayList

//get text from textview
time = date.getText().toString();
entry_d = entry.getText().toString();
dayNa         


        
相关标签:
3条回答
  • 2020-12-02 10:45

    Convert your array or object to Json with Gson library and store your data as String in json format.

    Save;

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    Editor editor = sharedPrefs.edit();
    Gson gson = new Gson();
    
    String json = gson.toJson(arrayList);
    
    editor.putString(TAG, json);
    editor.commit();
    

    Read;

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    Gson gson = new Gson();
    String json = sharedPrefs.getString(TAG, "");
    Type type = new TypeToken<List<ArrayObject>>() {}.getType();
    List<ArrayObject> arrayList = gson.fromJson(json, type);
    
    0 讨论(0)
  • 2020-12-02 10:50

    Store Arraylist Using Shared Preferences

    SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
    Editor edit=prefs.edit();
    
    Set<String> set = new HashSet<String>();
    set.addAll(your Arraylist Name);
    edit.putStringSet("yourKey", set);
    edit.commit();
    

    Retrieve Arraylist from Shared Preferences

    Set<String> set = prefs.getStringSet("yourKey", null);
    List<String> sample=new ArrayList<String>(set);
    
    0 讨论(0)
  • 2020-12-02 10:51

    Don't use Hashset for this. It will change the ordering of Arraylist. Use Gson instead. If you wish to use Hashset, you will have to serialize and deserialize which will take up resources.

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