How to iterate through all keys of shared preferences?

Eugene Chumak picture Eugene Chumak · Feb 16, 2012 · Viewed 44.2k times · Source

SharedPreferences have method getAll, but it returns no entries despite the fact some keys exist:

PreferenceManager.getDefaultSharedPreferences(this).contains("addNewAddress");

returns true

Map<String, ?> keys=PreferenceManager.getDefaultSharedPreferences(this).getAll();

returns empty map

What is wrong? How to get list of all shared preferences?

Answer

Lalit Poptani picture Lalit Poptani · Feb 16, 2012

What you can do is use getAll() method of SharedPreferences and get all the values in Map<String,?> and then you can easily iterate through.

Map<String,?> keys = prefs.getAll();

for(Map.Entry<String,?> entry : keys.entrySet()){
            Log.d("map values",entry.getKey() + ": " + 
                                   entry.getValue().toString());            
 }

For more you can check PrefUtil.java's dump() implementation.