Storing a String array in the SharedPreferences

后端 未结 3 1601
盖世英雄少女心
盖世英雄少女心 2020-12-28 21:52

I was wondering if it could be possible to save in the shared preferences an array of Strings, in a way that, every time we save a certain String, we store it in that array.

3条回答
  •  既然无缘
    2020-12-28 22:36

    You could make the array a JSON array and then store it like this:

    SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
    SharedPreferences.Editor editor = settings.edit();
    
    JSONArray jArray = new JSONArray();
    try {
        jArray.put(id);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
    editor.putString("jArray", jArray.toString());
    editor.commit();
    

    You can then get the array like this:

    SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
    try {
        JSONArray jArray = new JSONArray(settings.getString("jArray", ""));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

    Just an alternative solution that I have used in the past

提交回复
热议问题