Reputation: 1522
I create a few ArrayLists during one of my activities. When I leave the activity and come back to it, they come up as null. From some research, SharedPreferences is the way to overcome this. How do I go about this; do I have to save it as a HashMap? is SharedPreferences it's own method or do I do it within another specific method?
Upvotes: 0
Views: 759
Reputation: 1809
Here, how to write on Shared Preferences:
SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
//if your codes in your activity class, you dont need getActivity so you should use this
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_string_key", yourValue);
editor.commit();
Here, how to read from Shared Preferences:
SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
//same here. If your codes in your activity don't write "getActivity." part
int yourSavedValue = sp.getInt("your_string_key", defaultValue);
//defaultValue mean if there is no value with that key, it will return defaultValue.
If you'd like to learn more about it here you can get more information.
Answer to your new updated question:
As you can see my answer there is defaultValue.
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Set<String> tempSet = settings.getStringSet(FIRST_LIST, "");
Set<String> temp2Set = settings.getStringSet(SECOND_LIST, "");
//if it is first time it will return null. So your app going crash. To avoid that make a default value. Like this.
for (String str : tempSet)
firstList.add(Uri.parse(str));
for (String str : temp2Set)
secondList.add(Uri.parse(str));
Upvotes: 1
Reputation: 716
** you have convert this array to gson.
** First pass your array in parameter public void saveArrayList(ArrayList list, String key)
** now create object of SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
** now convert to gson :
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
Upvotes: 0
Reputation: 83537
You have at least three options:
Use a SharedPreferences object as you suggest in your question.
Use a SQLite database.
Use a file with your own format.
For an introduction to each of these options, read Storage Options.
Upvotes: 1