Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Current value to EditTextPreference for the first time

I am developing an android application where I am using Preference Fragment. In that Preference(For Settings) Fragment I have two EditTextPreference to change firstname and last name. What I need is, I want to display the current firstname and lastname to EditTextPreference when I first load the preference fragment so that the user can view their current firstname and lastname, and can change accordingly based on that.

like image 317
Lincy David Avatar asked Jun 28 '26 03:06

Lincy David


1 Answers

When you create edittext Preference in xml file at that time you can set default value and summary.

<EditTextPreference
             ....
             android:key="key_firstname"
             android:defaultValue="Lincy"
             android:summary="Lincy"/>   

You can set this for both first name and last name edittext preferences. It will display value when you load preference activity for first time.

Now you can use below code in your preference fragment so that whenever you update edittext preference value, it will always display latest value in summary.

EditTextPreference firstname =  (EditTextPreference) findPreference("key_firstname");
firstname .setSummary(sharedPreferences.getString("key_firstname","Lincy"));

EditTextPreference lastname=  (EditTextPreference) findPreference("key_lastname");
lastname.setSummary(sharedPreferences.getString("key_lastname","Laiju"));

To set value of edittext Preference use below code.

SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
editor.putString("key_firstname","userfirstname"); // You can pass you username value here
editor.putString("key_lastname","userlastname"); // You can pass you username value here
editor.commit();
like image 127
Pooja Avatar answered Jun 29 '26 17:06

Pooja