Save ArrayList to SharedPreferences

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

    As @nirav said, best solution is store it in sharedPrefernces as a json text by using Gson utility class. Below sample code:

    //Retrieve the values
    Gson gson = new Gson();
    String jsonText = Prefs.getString("key", null);
    String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson
    
    
    //Set the values
    Gson gson = new Gson();
    List textList = new ArrayList(data);
    String jsonText = gson.toJson(textList);
    prefsEditor.putString("key", jsonText);
    prefsEditor.apply();
    

提交回复
热议问题