Domanda

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
È stato utile?

Soluzione

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

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top