0

How do we store a user input in the EditTextPreference Box using preferences and retrieve it to use later on.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
this.editPreference = (EditTextPreference)getPreferenceScreen().findPreference("userPass");

This is my code. But it keeps crashing saying that preferenceScreen cannot be cast to a editTextPreference. Any ideas?

Thanks.!

LOGCAT:

 07-19 17:14:23.028: E/AndroidRuntime(7032): FATAL EXCEPTION: main
07-19 17:14:23.028: E/AndroidRuntime(7032): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.contact/com.example.contact.PrefsActivity}: java.lang.ClassCastException: android.preference.PreferenceScreen cannot be cast to android.preference.EditTextPreference
user2511882
  • 9,022
  • 10
  • 51
  • 59

1 Answers1

1

As noted in this artcle, you'll have to use EditTextPreference.getText().toString() if you need a string value. You can then save it to a local variable or to a database if necessary.

Edit

Writing your code:

protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     addPreferencesFromResource(R.xml.prefs);
     String userPreference = this.editPreference.getText(); // variable set to String value of text entered in widget

}
Phoenix
  • 1,881
  • 5
  • 20
  • 28
  • Can u suggest what change should be made to the code i posted? – user2511882 Jul 19 '13 at 21:24
  • I edited my answer to show you how I would set it up. You can then use the local variable `userPreference` if you need to populate a TextView or get certain characters or store it in a database. – Phoenix Jul 19 '13 at 21:29
  • How can there be an ID in the R folder if i am using prefs.xml from the XML folder – user2511882 Jul 19 '13 at 21:32
  • You're right, I wasn't thinking. The string is stored when the user enters it, so you can grab it right from the widget prompted by your xml reference. – Phoenix Jul 19 '13 at 21:36
  • Using the updated edit you made causes the app to crash with a null pointer exception – user2511882 Jul 19 '13 at 21:39
  • Well, you didn't provide much code, but if you are trying to access the variable during onCreate, it would give a Null Pointer due to the user not having entered a value. When the user enters the value in the dialog box EditText the preference is saved to Shared Preferences. I assume `editPreference` is the actual EditText widget, however if it is simply the call to the Preference Resource, then you'll need to get at the actual widget it self, which would be `this.editPreference.getEditText().getText().toString()` – Phoenix Jul 19 '13 at 21:48