How to check if SharedPreferences exists or not

AndroidSharedpreferences

Android Problem Overview


I'm checking in this way if the file exists, but I need to go beyond, I need to know if there is one in specific, is there any way?

File f = new File("/data/data/com.eventrid.scanner/shared_prefs/Eventrid.xml");
		  if (f.exists()){

		  }
		  else{
			  
		  }  

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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();
	}  

Solution 3 - Android

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.

Solution 4 - Android

You can try this

 fun checkLoginInfo(): Boolean{
    val saveLogin = sharedPreferences.getBoolean(SAVE_LOGIN, false)
    return saveLogin
}

 Checks whether the preferences contains a preference. 
 @param(SAVE_LOGIN) key The name of the preference to check.
 @param(false) default
 @return Returns true if the preference exists in the preferences, otherwise false.

Solution 5 - Android

Check if SharedPreferences key exists:

    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    if(mPrefs.getAll().containsKey("KeyName")){

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNico1991View Question on Stackoverflow
Solution 1 - AndroidYjayView Answer on Stackoverflow
Solution 2 - AndroidChris SpragueView Answer on Stackoverflow
Solution 3 - AndroidJuan José Melero GómezView Answer on Stackoverflow
Solution 4 - AndroidCydView Answer on Stackoverflow
Solution 5 - AndroiddanyapdView Answer on Stackoverflow