2015-08-26 193 views
-1

我想一個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的將是非常specefic有錯誤,但我無法弄清楚究竟這是什麼錯誤表示。

+0

會添加paranthesis幫助! (EditText)(getActivity()。findViewById(R.id.editText))。 忽略,如果它愚蠢:) – Ramesh

+0

其中id editText'聲明? – Blackbelt

回答

0

getActivity()可能爲null。轉移testMethod的調用。覆蓋片段中的onAttach並從那裏調用它。再次閱讀片段生命週期。

+0

getActivity()不爲空,因爲吐司工作正常(如果我刪除的是textwatcher) – JPJens