片段内的线程处理程序上的空指针

时间:2013-07-15 00:43:16

标签: android multithreading android-fragments handler

我想将此片段作为后台线程运行,因此所做的任何处理都不会影响主UI线程,但是我在行上获得了空指针异常

 handler.post(new Runnable() {

我迷路了,我该如何解决这个问题?这是堆栈跟踪

07-15 09:34:36.534:E / AndroidRuntime(6905):致命异常:Thread-5235 07-15 09:34:36.534:E / AndroidRuntime(6905):java.lang.NullPointerException 07-15 09:34:36.534:E / AndroidRuntime(6905):at com.example.asynctaskprogressbarexample.FragmentHeadlessFragment $ 1.run(FragmentHeadlessFragment.java:37)

代码的其余部分

 public class FragmentHeadlessFragment extends Fragment {

private OnTimeRequestedListener listener;
Activity activity;
Handler handler;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    new Thread(){

        public void run() {

        SystemClock.sleep(3000);

        handler.post(new Runnable() {  // <-- NULL POINTER EXCEPTION THIS LINE
            @Override
            public void run() {

                passData("test string from fragment with 3 second delay");
            }
         });


         } // end run

  }.start(); 


} // end onCreate

 @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);

    if (activity instanceof OnTimeRequestedListener) {
      listener = (OnTimeRequestedListener) activity;
    } else {
      throw new ClassCastException(activity.toString()
          + " must implement OnTimeRequestedListener");
    }
  }

@Override
 public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
  activity = getActivity();
  setRetainInstance(true);


 }

 public interface OnTimeRequestedListener {
        public void passSystemTime(String timeNumberString);

  }

 public void passData(String data) {
        listener.passSystemTime(data);
    }


}

2 个答案:

答案 0 :(得分:1)

您似乎没有在onCreate()中初始化处理程序。

答案 1 :(得分:0)

你永远不会初始化处理程序,你可以调用Handler handler = getWindow()。getDecorView()。getHandler();