导航抽屉片段 - TextWatcher崩溃

时间:2015-08-26 16:08:19

标签: android android-fragments android-studio textwatcher

我正在尝试将TextWatcher方法添加到通过导航抽屉加载的片段中:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    testMethod();
}

public void testMethod() {
    EditText tv_filter = (EditText) getActivity().findViewById(R.id.editText);
    tv_filter.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
            Toast.makeText(getActivity(), "INPUT TRACKED", Toast.LENGTH_SHORT).show();
        }
    });
}

问题是,无论何时加载此片段,应用程序都会崩溃并显示以下logcat消息:

    08-26 12:00:26.553  12842-12842/fest.test.dk.fest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: fest.test.dk.fest, PID: 12842
java.lang.NullPointerException
at fest.test.dk.fest.menuFragment.testMethod(menuFragment.java:74)
at fest.test.dk.fest.menuFragment.onCreate(menuFragment.java:66)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1766)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

通常logcat对于错误会非常精确,但我无法确切地知道这个错误意味着什么。

1 个答案:

答案 0 :(得分:0)

getActivity()可能为null。转移testMethod的调用。覆盖片段中的onAttach并从那里调用它。再次阅读片段生命周期。