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.
Open the device monitor by clicking it. Then you need to select the File Explorer tab in the device monitor. Find the data folder and find another data folder inside it. It will contain a folder having the name of your application package and there will be the desired SharedPreferences.
Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With