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);
}
}
Okay guys, I got it:
import android.preference.EditTextPreference;
public class Settings extends PreferenceActivity {
EditTextPreference weightEditTextPreference;
EditTextPreference ageEditTextPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
weightEditTextPreference = (EditTextPreference)findPreference("weight");
ageEditTextPreference = (EditTextPreference)findPreference("age");
SharedPreferences getWeightAndAgeStore = getSharedPreferences("weightAndAgeStorage", Context.MODE_PRIVATE);
weightEditTextPreference.setText(getWeightAndAgeStore.getString("weight", "0"));
ageEditTextPreference.setText(getWeightAndAgeStore.getString("age", "0"));
What this does is that it sets the EditText box to the SharedPreferences
' saved key (in this case, weight
and age
of WeightAndAgeStorage
) data in the dialog that pops up when you press it.
Hope anyone else reading this now or in the future (but what about the past?) benefits from this finding.
Cheers!
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