ImagineThat ImagineThat - 4 months ago 22
Java Question

Saving ArrayList<Uri> to SharedPreferences

I have multiple arraylists of URIs to store/fetch in SharedPreferences. I first change them to StringSets to store and on retrieval I loop through and parse each string back to a URI and into the arraylist.

1) What if it's my first time opening the app? I get a NullPointerException when trying to use the tempSet and temp2set in my fetching. I assume this is because I haven't yet added anything to my prefs.

2) Am I correctly adding multiple arrays in my onStop using editor.putStringSet twice with different keys?

The following is near the beginning of my onCreate:

// Restore preferences
SharedPreferences settings = getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Set<String> tempSet = settings.getStringSet(FIRST_LIST, null);
Set<String> temp2Set = settings.getStringSet(SECOND_LIST, null);
for (String str : tempSet)
firstList.add(Uri.parse(str));
for (String str : temp2Set)
secondList.add(Uri.parse(str));


I followed the android API's example for most of the following:

@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREF_FILE, 0);
SharedPreferences.Editor editor = settings.edit();
Set<String> tempSet = new HashSet(happyList);
Set<String> temp2Set = new HashSet(happyList);
editor.putStringSet(FIRST_LIST, tempSet);
editor.putStringSet(SECOND_LIST, temp2Set);
editor.commit();
}

Answer

Solution is to write conditions to work on the sets only if they aren't null:

// Restore preferences
SharedPreferences settings = getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Set<String> tempSet = settings.getStringSet(FIRST_LIST, null);
Set<String> temp2Set = settings.getStringSet(SECOND_LIST, null);
if(tempSet != null)
    for (String str : tempSet)
        firstList.add(Uri.parse(str));
if(temp2Set != null)
    for (String str : temp2Set)
        secondList.add(Uri.parse(str));