MXG123
MXG123

Reputation: 197

Setting sharedpreferences default value

I am using the following methods to save and read user settings:

    private void saveUserSettings(){
    SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = userSettings.edit();
    editor.putInt("timeOne",timeOne);
    editor.apply();
}

private int getUserSettings(){
        SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
        timeOne = userSettings.getInt("timeOne",timeOne);       
    }

Then in onCreate the following:

SharedPreferences prefs = getSharedPreferences("userSettings", Context.MODE_PRIVATE);

This is fine and the data is saved when the app relaunches. However I want to have default data when the app is installed initially it seems to be that the values should be stored in an xml file.

I have created the following file under res/xml/preferences.xml

    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference
        android:key="timeOne"
        android:defaultValue="2"/>
</PreferenceScreen>

Then in onCreate:

PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

I changed the "userSettings" to preferences to match up but this dosen't work and returns a value of zero. Is this method of reading the xml file ok or/and am I overlooking something?

Upvotes: 2

Views: 2520

Answers (1)

Juan
Juan

Reputation: 5589

I think you are overcomplicating yourself.

In this instruction the second parameter is the default to use if there is no shared preference with that name.

You just need to set that value to the default you need.

timeOne = userSettings.getInt("timeOne",<Put here the default value>);

EDIT I

Lets say the default value if it is the first time the app runs and there is no setting saved yet, is 2.

The method that reads the value should be like this.

private int getUserSettings(){
        SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
        timeOne = userSettings.getInt("timeOne",2);       
}

Upvotes: 2

Related Questions