How to save and get ArrayList into SharedPreference

Hey,
I’m gonna show you very basic but useful way to save and get ArrayList from SharedPreference.
Markdown:
    /**
     *     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);
    }
Gist:

    /**
     *     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);
    }

We have two methods to save and get ArrayList from SharedPreference. First, we need to save our ArrayList, we have two parameters which are our own ArrayList and our key. We need to get that key as a parameter because it lets us to use this method more than one ArrayList. Therefore, we won’t need to write one than one Shared method to save each array. We just need to change key’s name and save that arraylist as a new one.
Second, we just need the same key to get and return that ArrayList from SharedPreference. Actually this is so simple because GSON makes the whole job for us.
Actually this method did not save your ArrayList as itself, it converts the ArrayList to the JSON format and when you want to get it, you just re-convert to the ArrayList.
Ta-daa :P That’s it, so simple so elegant :P

GSON Library

If you’re getting error for GSON. Here is how to solve it. You need to implement the GSON library from Google.
dependencies {        implementation 'com.google.code.gson:gson:2.8.5'}
If you have question, ask me :)

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...