How to check if SharedPreferences file exists or not

Viewed 31805

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.

7 Answers

It seems to be a more accurate solution

val file = File(filesDir.parent, "shared_prefs/name_of_preference.xml")

or just

val file = File(filesDir, "../shared_prefs/name_of_preference.xml")
Related