Save ArrayList to SharedPreferences

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

    Android SharedPreferances allow you to save primitive types (Boolean, Float, Int, Long, String and StringSet which available since API11) in memory as an xml file.

    The key idea of any solution would be to convert the data to one of those primitive types.

    I personally love to convert the my list to json format and then save it as a String in a SharedPreferences value.

    In order to use my solution you'll have to add Google Gson lib.

    In gradle just add the following dependency (please use google's latest version):

    compile 'com.google.code.gson:gson:2.6.2'
    

    Save data (where HttpParam is your object):

    List httpParamList = "**get your list**"
    String httpParamJSONList = new Gson().toJson(httpParamList);
    
    SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(**"your_prefes_key"**, httpParamJSONList);
    
    editor.apply();
    

    Retrieve Data (where HttpParam is your object):

    SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
    String httpParamJSONList = prefs.getString(**"your_prefes_key"**, ""); 
    
    List httpParamList =  
    new Gson().fromJson(httpParamJSONList, new TypeToken>() {
                }.getType());
    

提交回复
热议问题