Skip to content

Instantly share code, notes, and snippets.

@WrathChaos
Last active July 13, 2021 18:40
Show Gist options
  • Save WrathChaos/5f39e3ce3874a049d25e2ca8958d18b6 to your computer and use it in GitHub Desktop.
Save WrathChaos/5f39e3ce3874a049d25e2ca8958d18b6 to your computer and use it in GitHub Desktop.
How to save and get ArrayList in SharedPreference on Android? Article: https://freakycoder.com/android-notes-40-how-to-save-and-get-arraylist-into-sharedpreference-7d1f044bc79a
    /**
     *     Save and get ArrayList in SharedPreference
     */

    public void saveArrayList(ArrayList<String> 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();     // This line is IMPORTANT !!!
    }

    public ArrayList<String> getArrayList(String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        return gson.fromJson(json, type);
    }
@Dencer
Copy link

Dencer commented May 30, 2018

super

@nathan-mersha
Copy link

nice, thanks

@samirsamedow
Copy link

samirsamedow commented Oct 12, 2018

Thanks for the share. but how to delete saved list?. editor.remove(key) not worked

@pbwauyo
Copy link

pbwauyo commented Mar 2, 2019

Thanks for the share. but how to delete saved list?. editor.remove(key) not worked

try editor.remove(key).apply()

@amanaggarwal1
Copy link

great work there

@MadhavSapkota
Copy link

How to display that saved array in list view??

@WrathChaos
Copy link
Author

How to display that saved array in list view??

You need to google it for that :) Not the right place to ask :)

@oremlawi
Copy link

How to work with ArrayList ?

Note that CustomClass has Date, Int and String fields

@WrathChaos
Copy link
Author

Hey @oremlawi,
I really could not understand your question. Can you explain it a bit?

@deva-25
Copy link

deva-25 commented Apr 23, 2021

Am using it on a fragment page... But the data is not loading back.

@thanhdat410
Copy link

Phenomenal !! U saved me

@WrathChaos
Copy link
Author

Love to hear that @thanhdat410 :)

I suggest you to write a simple util class to use them a much better way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment