How to iterate over all keys of general settings?

SharedPreferences has a getAll method, but it does not return any records, despite the fact that some keys exist:

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

returns true

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

returns a blank card

What's wrong? How to get a list of all common settings?

+61
android sharedpreferences
Feb 16 '12 at 11:27
source share
2 answers

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

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

You can check the PrefUtil.java's dump() implementation for more details.

+153
Feb 16 '12 at 11:44
source share

I think this question is more related to why

  PreferenceManager.getDefaultSharedPreferences(this).getAll() 

returns a blank / inconsistent display than with how to iterate over a standard java map. The android doc is actually not very clear what is going on here, but basically it looks like the first call on

  PreferenceManager.setDefaultValues(this, R.xml.preferences,false) 

- this is what you must call to initialize preferences when starting the application - it creates some kind of cached version of your preferences, which leads to the steady conversion of future changes to the xml settings file, i.e. causes the mismatch that you described in your question.

to reset this "cached object", follow these steps (which you can find from the link above):

  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().clear(); PreferenceManager.setDefaultValues(this, R.xml.preferences, true); 
+7
Feb 14 '13 at 17:05
source share



All Articles