chobo2 chobo2 - 3 months ago 40
Android Question

How to check if SharedPreferences file exists or not

I am looking an android Shared Preferences and I am wondering is there a way to just check if the preferences file exists.

SharedPreferences mySharedPreferences ;
mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode);


This above code leads me to believe that "Name_of_Your_preferene" is stored as a file or some sort of container that will contain your preferences.

I am wondering is there away to check if this exists or not. When a user loads up an activity I want to save all the settings into this file with some default values(off for all settings). However I only want to do this if they are going to the page for the first time.

Otherwise if I would do something like this every time the page loads up

SharedPreferences.Editor editor= mySharedPreferences.edit();

/* now store your primitive type values. In this case it is true, 1f and Hello! World */

editor.putBolean(“myBoolean”,true);

editor.putFloat(“myFloat”,1f);

editor.putString(“myString”,” Hello! World”);


I am guessing it would override all settings even ones they set.

Answer

The SharedPreferences are saved in a xml file. You can find it in /data/data/your_application_package/shared_prefs/Name_of_your_preference.xml

To check if the SharedPreferences 'Name_of_your_preference' exist :

File f = new File(
"/data/data/your_application_package/shared_prefs/Name_of_your_preference.xml");
if (f.exists())
    Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
else
    Log.d("TAG", "Setup default preferences");

Regards.