0

I am trying to retrieve data that is on SharedPreferences. It is mapped as key(name of the movie), value(HashSet, contains all information related to the movie), like this:

 SharedPreferences.Editor preferencesEditor = preferences.edit();
 preferencesEditor.putStringSet(movieInfo[1], new HashSet<String>(Arrays.asList(movieInfo)));
 preferencesEditor.commit();  

I want to fetch that HashSet to be able to use the information.
I was able to get to this:

SharedPreferences preferences = getContext().getSharedPreferences("favorites_list", Context.MODE_PRIVATE);
Map<String, String> map = (Map<String, String>) preferences.getAll();
String a = null;
for (Map.Entry<String, String> entry : map.entrySet()){
    a = entry.getValue();
}  

The problem is that getValue() returns a string so it has to be set to a string, but the value itself is a HashSet, so it returns a ClassCastException error that HashSet cannot be cast to String. Any thoughts?

Joao Pereira
  • 75
  • 2
  • 11

1 Answers1

1

After you get the HashSet, cast it and iterate through it to get the values

SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);        
for (Entry<String, ?> entry : appPreferences.getAll().entrySet()) {

    String key = entry.getKey();
    System.out.println("key " + key);
    System.out.println("value " + entry.getValue());

    if(key.equals("YOUR_KEY_NAME")) {
        if(entry.getValue() instanceof HashSet) {
            Set<String> set = (HashSet)entry.getValue();
            for(String s: set) {
                System.out.println(s);
            }
        }
        break;
    }
}
Jas
  • 11
  • 3