Saturday, November 25, 2017

Store ArrayList in SharedPreferences

Store ArrayList In SharedPreferences:


In Shared Preference, is it store arraylist ?, Usually in shared preference we have to store string but in this post we are going to see how to store arraylist in sharedpreference.


Method:1


SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();

String json = gson.toJson(arrayList);

editor.putString(TAG, json);
editor.commit();

Read;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);



Method: 2

SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
Editor edit=prefs.edit();

Set<String> set = new HashSet<String>();
set.addAll(your Arraylist Name);
edit.putStringSet("yourKey", set);
edit.commit();

Retrieve Arraylist from Shared Preferences

Set<String> set = prefs.getStringSet("yourKey", null);
List<String> sample=new ArrayList<String>(set);

No comments:

Post a Comment