简体   繁体   English

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

[英]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. 我已经在Android应用中实现了偏好设置屏幕。 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. 我想放置一个功能,使用户单击编辑文本首选项,如果他用“ CONFIRM”填充该字段,则应用程序的数据库将被清空,但我不知道如何从对话框中捕获用户输入。

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 这给了我一个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: 在使用preference之前,请尝试将preferenceEditTextPreference

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 . 在将侦听器设置为首选项时,您将获得NullPointerException ,这意味着您的首选项为null Check in your preferences XML if your key for preference matches argument in findPreference() method. 如果您的首选项键与findPreference()方法中的参数匹配,请检查您的首选项XML。

In your listener you are calling getText() on preference, which may return null as value you entered is not stored in preferences yet. 在您的侦听器中,您正在对首选项调用getText() ,因为您输入的值尚未存储在首选项中,所以它可能返回null By the way, when you are not using regular expressions to compare strings, you can use equals() instead of matches() . 顺便说一句,当您不使用正则表达式比较字符串时,可以使用equals()而不是matches()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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