Darshan Komu
Darshan Komu

Reputation: 186

Wanted to store this custom listview text using shared preference on user click

I want to store this custom listview text using shared preference when user will click on that star image (P.S - I don't want to use a database for this) and also wants to retrieve that text(all selected text as an ArrayList) in another activity. Now I am able to store this text as an ArrayList in my shared preference I but inside my getView() method of custom adapter my ArrayList get reinitialize again and again can anyone help me out Like this demo example

when user will click on this star image when user will click on this star image

and in favorite activity will retrieve ArrayList from shared preference and in favorite activity will retrieve ArrayList from shared preference

Upvotes: 0

Views: 88

Answers (1)

Nicolas M.
Nicolas M.

Reputation: 390

You have to write your arraylist as a json into 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();
        }

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

https://freakycoder.com/android-notes-40-how-to-save-and-get-arraylist-into-sharedpreference-7d1f044bc79a

Upvotes: 1

Related Questions