Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if SharedPreferences exists or not

People also ask

How do I find SharedPreferences?

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.

How check if shared preference exists in flutter?

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.

How can I check my data usage on SharedPreferences?

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.

How check shared preference is null?

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.