Reputation: 1088
I am trying to read data from EditTextPreference. Like below
Preference.xml
<PreferenceCategory android:title="@string/driver_info">
<EditTextPreference
android:dialogTitle="@string/driver_name"
android:key="driver_name"
android:title="@string/driver_name" />
</PreferenceCategory>
ConfigActivity.java
public class ConfigActivity extends PreferenceActivity implements OnPreferenceChangeListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConfigActivity.this);
final String driverName = prefs.getString("driver_name", null);
Log.d(TAG,"driverName-->"+driverName);
}
}
In the edit text i have entered aaaa and clicked OK button , but still receiving below log
ConfigActivity: driverName-->null
I just trying read the data from "test"(string). Please find attached screenshot for reference.
Can you please help me . How we will read editext string.
Upvotes: 2
Views: 597
Reputation: 2516
You can listen to changes with an OnPreferenceChangeListener. (I see that you have already implemented it in your class.) Then you can set the listener to your EditTextPreference like:
Preference driverNamePref = findPreference("driver_name")); //You can put this string key in string resources in fact
driverNamePref.setOnPreferenceChangeListener(this);
In the onPreferenceChange callback, you'll receive the new value entered by the user, so you can take a grasp of the new value and do whatever you want to do with that:
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//Get the newValue and do what you want to do with it
if (preference.getKey().equals("driver_name")) {
String driverName = (String) newValue;
...
}
}
Note also that onPreferenceChange callback is called before the new value is actually saved in the sharedPreferences. So you can also make data validation here if you need to. If data is not valid, you can show an error and return false, so new value won't be saved. If everything is all right return true and it will be saved to SharedPreferences.
Upvotes: 1