These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android. content. Context) with a context in the same package as this activity.
To check if a key or record is present in shared preferences we have to use containsKey() method. This methods takes key as value and checks if the key is present in sharedpreferences. If the key is present it will return true else it will return false.
Click on the package name for your application. After that click on the shared_prefs folder and inside that open the shared_prefs. xml file. Now you will get to see the data which we stored in our shared preferences from our application.
getSharedPreferences("myPrefs", MODE_WORLD_READABLE); String username = myPrefs. getString("USERNAME",null); String password = myPrefs. getString("PASSWORD",null); if username and password are present, they will have a value otherwise they will be null.
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
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With