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 ''

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

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 :

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