There are a lot of ways that we can use, there are :
- Using sharedPreference
- Using Intent, or
- 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
usage : String [] listItem = getListAsAString(Constants.KEY_SHARED);
Hope my description above help you. Thank you.
EmoticonEmoticon