Search code examples
androidsharedpreferencesdefault-value

Where are default shared preferences written to?


I am trying to initialise default shared preferences upon first run of my app. I found out that depending on how I do it, there are differences in the shared preferences file on the Android file system.

If I specifically write to the shared preferences with the following code, the XML file resides within /data/data/myapp/shared_prefs/:

SharedPreferences.Editor editor = pref.edit();
if ((myKey = pref.getString("key", null)) == null) {
  myKey = "default value";
  editor.putString("key", myKey );
  editor.commit();
}

However, if I use the following one-liner to initialize the default value, I don't see the XML file in /data/data/myapp/shared_prefs/:

myKey = pref.getString("key", "default value");

In the latter case, where is the XML file stored, and why is there a difference in behaviour?


Solution

  • I'll address your second case first:

    myKey = pref.getString("key", "default value");
    

    What you're saying here is "get the value associated with "key", or "default value" if nothing is". This is purely a read operation. When you get "default value" returned from this method, the system isn't actually "initializing" your shared preferences store, it's just saying "didn't find anything for "key", so here's that other thing you said".

    Next, your first case:

    SharedPreferences.Editor editor = pref.edit();
    if ((myKey = pref.getString("key", null)) == null) {
        myKey = "default value";
        editor.putString("key", myKey );
        editor.commit();
    }
    

    Here you do the same thing as above with regards to getString(), but this time you check its return value and then perform a write operation. The body of your if block is what's creating the file.