How to check if SharedPreferences file exists or not

You can use the contains method on the SharedPreferences object to check if one of your preference keys exist in the file. If this returns false, you can assume this is the first time and populate the default settings. The documentation for this method is here.

I couldn't find any way to check if a preference file already exists (it will be created automatically the first time you retrieve an editor), but this method should do the trick.


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.


I did not have enough reps to comment natur3's post. Therefore this answer.

@natur3: Very helpful, thankyou. I hade a small problem however... with the file suffix. If i define my filename like this:

    private static final String FILENAME = "myPrefs";

And then use:

    File f = new File("/data/data/" + getPackageName() +  "/shared_prefs/" + FILENAME);

f.exists() will return false even if the file exists on the filesystem. This is because Android will add the ".xml" suffix automatically when writing SharedPreferences so i had to make my file reference look like this:

    File f = new File("/data/data/" + getPackageName() +  "/shared_prefs/" + FILENAME + ".xml");

for it to work. I don't know where u got your "_preferences.xml" suffix from.

I managed to figure this out by browsing the emulator filesystem in Eclipse using Window->Show View->Other... and then select "File Explorer".