This time in the same project I'm facing a slightly challenging issue where in settings.xml file in the res/xml folder:
<EditTextPreference
android:key="weight"
android:title="@string/update_user_weight"
android:persistent="true"
android:dialogTitle="@string/update_user_weight"
android:dialogMessage="@string/update_user_weight_message"
android:defaultValue="" />
<EditTextPreference
android:key="age"
android:title="@string/update_user_age"
android:persistent="true"
android:dialogTitle="@string/update_user_age"
android:dialogMessage="@string/update_user_age_message"
android:defaultValue="" />
and in a class file UserData.java:
SharedPreferences storeWeightAndAge = getSharedPreferences("WeightAndAgeStorage", Context.MODE_PRIVATE);
Editor store = storeWeightAndAge.edit();
store.putString("weight", weightData);
store.putString("age", ageData);
store.commit();
What I'm trying to do here is to set the above two EditTextPreferences' android:defaultValue
to stored weight
and age
in the SharedPreferences
respectively.
Now, how do I go about doing that?
EDIT: provided Settings.java file that uses the settings.xml file:
package com.example.drinkup;
import android.content.SharedPreferences;
import android.os.*;
import android.preference.PreferenceFragment;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class Settings extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Firstly, set the default value for EditTextPreference
. The value will be stored as a String
type. For example:
<EditTextPreference
android:key="weight"
android:defaultValue="enter your value (54)"
... />
<EditTextPreference
android:key="age"
android:defaultValue="enter your value"
... />
Then, apply the default value in activity where your app's activity is started first (once installed for first). For example, in the MainActivity
's onCreate()
method:
PreferenceManager.setDefaultValue(this, R.xml.settings, false);