Search code examples
androidsharedpreferences

How to save Array list with model class in shared preference?


private ArrayList<PhotoInfo> imagelist;


imagelist = new ArrayList<>();

imagelist = response.body().getPhotos();

I have to save images in shared preference

and retrieve from as Arraylist


Solution

  • Hey I made this easy methods for Save & Get any custom model's ArrayList into SharedPreferences.

    Gson dependency required for this:

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

    Save any custom list into SharedPreferences:

    public void saveMyPhotos(ArrayList<PhotoInfo> imagelist ) {
        SharedPreferences  prefs = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = prefs.edit();
        try {
            Gson gson = new Gson();
            String json = gson.toJson(imagelist);
            editor.putString("MyPhotos", json);
            editor.commit();     // This line is IMPORTANT !!!
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    Get all my saved photos from SharedPreferences:

    private ArrayList<PhotoInfo> getAllSavedMyPhotos() {
        SharedPreferences  prefs = PreferenceManager.getDefaultSharedPreferences(this);    
        Gson gson = new Gson();
        String json = prefs.getString("MyPhotos", null);
        Type type = new TypeToken<ArrayList<PhotoInfo>>() {}.getType();
        return gson.fromJson(json, type);
    }