Search code examples
androidsharedpreferencespreferencespersist

Android preferences: get all set values when keys are unknow


Can someone tell me please how can I get all string set values from a preference file, I saved in this file just set lists?

Set<String> set = new HashSet<String>(); 
set.add("value1");
set.add("value2");
set.add("value3");
editor.putStringSet("key", set);

The problem I don't know which key will be chosen to save. Is this possible to read all available set lists without knowing the keys?


Solution

  • You can use something like this.

    Map<String, ?> keys = PreferenceManager.getDefaultSharedPreferences(this).getAll();
    for (Map.Entry<String, ?> entry : keys.entrySet()) {
        if (entry.getValue() instanceof Set) {
            Log.e("Set values", entry.getKey() + ": " +
                    entry.getValue().toString());
        }
    }
    

    Although am not sure why would you want to do that? Because you should set the data with some specific keys, so that you can fetch the same at a later time. What do you mean by I don't know which key will be chosen to save?