Save ArrayList to SharedPreferences

前端 未结 30 3559
野的像风
野的像风 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:22

    /**
     *     Save and get ArrayList in SharedPreference
     */
    

    JAVA:

    public void saveArrayList(ArrayList list, String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();    
    
    }
    
    public ArrayList getArrayList(String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken>() {}.getType();
        return gson.fromJson(json, type);
    }
    

    Kotlin

    fun saveArrayList(list: java.util.ArrayList?, key: String?) {
        val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
        val editor: Editor = prefs.edit()
        val gson = Gson()
        val json: String = gson.toJson(list)
        editor.putString(key, json)
        editor.apply()
    }
    
    fun getArrayList(key: String?): java.util.ArrayList? {
        val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
        val gson = Gson()
        val json: String = prefs.getString(key, null)
        val type: Type = object : TypeToken?>() {}.getType()
        return gson.fromJson(json, type)
    }
    

提交回复
热议问题