如何从Edittext首选项中捕获用户输入?

时间:2018-01-09 17:38:21

标签: java android nullpointerexception

不要将此标记为重复,因为我在互联网上找不到任何有用的内容。

我已在我的Android应用中实现了首选项屏幕。我想在用户点击编辑文本首选项时添加一个功能,如果他填充该字段 " CONFIRM" 然后应用程序的数据库将被清空,但我不知道如何从对话框中捕获用户输入。

到目前为止我有什么

if (preference instanceof EditTextPreference) {

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

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

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

                    }

                }

            }

给我一个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)

我的设置活动全码

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;
    }
};

}

我们将非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

在使用之前尝试将preference投射到EditTextPreference

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

希望它有所帮助。

答案 1 :(得分:0)

您在设置首选项的侦听器时收到NullPointerException,这意味着您的首选项为null。如果您的首选项键与findPreference()方法中的参数匹配,请检查首选项XML。

在您的监听器中,您在首选项上调用getText(),可能会返回null,因为您输入的值尚未存储在首选项中。顺便说一下,当您不使用正则表达式来比较字符串时,可以使用equals()代替matches()

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