How to check if SharedPreferences exists or not
Well, one could do:
SharedPreferences sharedPrefs = getSharedPreferences("sp_name", MODE_PRIVATE);
SharedPreferences.Editor ed;
if(!sharedPrefs.contains("initialized")){
ed = sharedPrefs.edit();
//Indicate that the default shared prefs have been set
ed.putBoolean("initialized", true);
//Set some default shared pref
ed.putString("myDefString", "wowsaBowsa");
ed.commit();
}
SharedPreferences
has a contains(String key)
method, which can be used to check if an entry with the given key exists.
http://developer.android.com/reference/android/content/SharedPreferences.html
Another solution:
If you know the exact number of preferences you have you can:
public void isPreferencesSet(Context context){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return (sharedPreferences.getAll().size() == exactNumberOfPreferences);
}
This works because the preferences file stored in /data/data/myApp/shared_prefs/myApp_prefrences.xml contains a preference's value pair only if its value has been set.