我想将此片段作为后台线程运行,因此完成的任何处理都不会影响主 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): 在 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);
}
}