Thursday, December 29, 2016

Android Store And Retrieve List To/From SharedPreference

In development, we sometimes need a temporary storage to store our data. Temporary storage used to passing our value from one activity to other activity.

There are a lot of ways that we can use, there are :
  1. Using sharedPreference
  2. Using Intent, or
  3. Using SQLite database
For SQLite database your can read here : Android SQLite Database Tutorial

If we need to passing a single value to other activity, we pretty quiet use Intent or sharedPreference. Both of those have a method to store a single value
  • SharedPreference : putString("","")
  • Intent : putExtra("","")
But in other condition we have to passing list to other activity, how to do it? 


Well, this tutorial going to show you how to store a List or ArrayList in SharedPrefences. But we have compile Gson in our build.gradle(Module:app)

compile 'com.google.code.gson:gson:2.6.2'

Gson used to convert list or arraylist as string (toJson()) before store to the shared preferences. Here the method to store list on sharedPrefences :



/**
* this method used to save list as a string using gson
* @param context
* @param key
* @param value
* @return
*/
private String saveListAsAString(Context context, String key, List<String> value){
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MODE_SHARED, Context.MODE_PRIVATE);
final SharedPreferences.Editor edit = sharedPreferences.edit();
final Gson gson = new Gson();
String jsonString = gson.toJson(value);
edit.putString(key,jsonString);
edit.commit();
return jsonString;
}
view raw store.java hosted with ❤ by GitHub
And when we try to retrieve the data, we have to convert the value that we get from sharedPreference become an arrayList, using Gson (fromJson()). Here the method to retrieve list from sharedPreference :

/**
* this method used to retrieve list as a string
* @param key
* @return
*/
private String[] getListAsAString(String key){
SharedPreferences sharedPreferences = getSharedPreferences(Constants.MODE_SHARED, Context.MODE_PRIVATE);
Gson gson = new Gson();
String [] stringArray;
String jsonString = sharedPreferences.getString(key, null);
stringArray = gson.fromJson(jsonString, String[].class);
return stringArray;
}
view raw retrieve.java hosted with ❤ by GitHub
Your can get the value as list by using like the following code :

usage : String [] listItem = getListAsAString(Constants.KEY_SHARED);
Hope my description above help you. Thank you.

Related Posts


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)