Save ArrayList to SharedPreferences

前端 未结 30 3580
野的像风
野的像风 2020-11-21 04:43

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves

30条回答
  •  清歌不尽
    2020-11-21 05:16

    You can save String and custom array list using Gson library.

    =>First you need to create function to save array list to SharedPreferences.

    public void saveListInLocal(ArrayList list, String key) {
    
            SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(list);
            editor.putString(key, json);
            editor.apply();     // This line is IMPORTANT !!!
    
        }
    

    => You need to create function to get array list from SharedPreferences.

    public ArrayList getListFromLocal(String key)
    {
        SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken>() {}.getType();
        return gson.fromJson(json, type);
    
    }
    

    => How to call save and retrieve array list function.

    ArrayList listSave=new ArrayList<>();
    listSave.add("test1"));
    listSave.add("test2"));
    saveListInLocal(listSave,"key");
    Log.e("saveArrayList:","Save ArrayList success");
    ArrayList listGet=new ArrayList<>();
    listGet=getListFromLocal("key");
    Log.e("getArrayList:","Get ArrayList size"+listGet.size());
    

    => Don't forgot to add gson library in you app level build.gradle.

    implementation 'com.google.code.gson:gson:2.8.2'

提交回复
热议问题