Store a List or Set in SharedPreferences

前端 未结 3 515
-上瘾入骨i
-上瘾入骨i 2020-12-03 07:15

My app has a list of String values (of some 5-20 characters each), that I have to store persistently. The SharedPreferences seem to me the most appropriate, as it\'s a short

相关标签:
3条回答
  • 2020-12-03 07:53

    Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.

    TinyDB tinydb = new TinyDB(context);
    

    to put

    tinydb.putList("MyUsers", mUsersArray);
    

    to get

    tinydb.getList("MyUsers");
    
    0 讨论(0)
  • 2020-12-03 07:53

    If you know the order of the list entries and/or it doesn't matter you can "glue" them all into a single String with a separator of your choice and then store it with SharedPreferences. After loading it back you would split the String into the entries based on your separator. Something like String listEntries = "enty1;entry2;entry3" (semicolon as separator in this case). But no idea about performance issues.

    0 讨论(0)
  • 2020-12-03 07:57

    I found the easiest solution to store and retrieve a list of items from SharedPreferences is to simply serialize / deserilaize the array into / from JSON and store it into a string setting.

    Gson comes really handy doing it.

    READ:

    SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
    String value = prefs.getString("list", null);
    
    GsonBuilder gsonb = new GsonBuilder();
    Gson gson = gsonb.create();
    MyObject[] list = gson.fromJson(value, MyObject[].class);
    

    WRITE:

    String value = gson.toJson(list);
    SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
    Editor e = prefs.edit();
    e.putString("list", value);
    e.commit();
    
    0 讨论(0)
提交回复
热议问题