简体   繁体   中英

How to catch user input from Edittext Preference?

Don't mark this as duplicate because I could not find anything useful on the internet.

I have implemented a preferences screen in my android app. I want to put a feature where the user clicks on an edit text preference and if he fills the field with "CONFIRM" then the app's database will be emptied but I don't know how to catch user input from the dialog.

What I have so far

if (preference instanceof EditTextPreference) {

                if (preference.getKey().matches("pref_reset_savings")){

                    if(((EditTextPreference) preference).getText().matches("CONFIRM")){

                        Log.i("reset", "confirmed");

                    }

                }

            }

That Gives Me A NullPointerException

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.musa.mymoneybox/activities.Settings}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.preference.Preference.setOnPreferenceChangeListener(android.preference.Preference$OnPreferenceChangeListener)' on a null object reference
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                     at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                     at android.os.Looper.loop(Looper.java:164)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.preference.Preference.setOnPreferenceChangeListener(android.preference.Preference$OnPreferenceChangeListener)' on a null object reference
                                                                     at activities.Settings.bindPreferenceSummaryToValue(Settings.java:49)
                                                                     at activities.Settings.access$000(Settings.java:14)
                                                                     at activities.Settings$PrefFragment.onCreate(Settings.java:40)
                                                                     at android.app.Fragment.performCreate(Fragment.java:2593)
                                                                     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1234)
                                                                     at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2415)
                                                                     at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2194)
                                                                     at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2148)
                                                                     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2049)
                                                                     at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3044)
                                                                     at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2991)
                                                                     at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:178)
                                                                     at android.app.Activity.performCreateCommon(Activity.java:6969)
                                                                     at android.app.Activity.performCreate(Activity.java:6977)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)

My Settings Activity Fullcode

package activities;

import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;

import com.musa.mymoneybox.R;

import configs.AppCompatPreferenceActivity;

public class Settings extends AppCompatPreferenceActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    android.support.v7.app.ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    this.runOnUiThread(new Runnable() {
        public void run() {

    //Load Settings Fragment
    getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefFragment()).commit();

}});

}

public static class PrefFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_main);

        bindPreferenceSummaryToValue(findPreference("pref_sound"));

        bindPreferenceSummaryToValue(findPreference("pref_notifications"));

    }
}

private static void bindPreferenceSummaryToValue(Preference preference) {

    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getBoolean(preference.getKey(), true));
}

private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {

        if (newValue instanceof Boolean) {
            boolean isChecked = (boolean) newValue;

            if(preference.getKey().matches("pref_notifications")){


                if (isChecked){

                    Log.i("Notifications", "True");

                } else {

                    Log.i("Notifications", "False");
                }
            }

            if (preference instanceof EditTextPreference) {

                if (preference.getKey().matches("pref_reset_savings")){

                    if(((EditTextPreference) preference).getText().matches("CONFIRM")){

                        Log.i("reset", "confirmed");

                    }

                }

            }

        }

        return true;
    }
};

}

Any help would be deeply appreciated!

Try to cast preference to EditTextPreference before using it:

if (preference instanceof EditTextPreference) {
EditTextPreference newPreference = (EditTextPreference) preference;
    if (newPreference.getKey().matches("pref_reset_savings")){
        if(newPreference.getText().matches("CONFIRM")){
            Log.i("reset", "confirmed");
        }
    }
}

Hope it helps.

You are getting NullPointerException while setting listener for preference, which means your preference is null . Check in your preferences XML if your key for preference matches argument in findPreference() method.

In your listener you are calling getText() on preference, which may return null as value you entered is not stored in preferences yet. By the way, when you are not using regular expressions to compare strings, you can use equals() instead of matches() .

if (newValue.equals("CONFIRM")){
    Log.i("reset", "confirmed");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM