Reputation: 9351
I wanted to run this fragment as a background thread so any processing done does not effect the main UI thread, however I am getting a null pointer exception on the line
handler.post(new Runnable() {
I am lost, how do i fix this? here is the stack trace
07-15 09:34:36.534: E/AndroidRuntime(6905): FATAL EXCEPTION: 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)
the rest of the code
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);
}
}
Upvotes: 1
Views: 2099
Reputation: 54
You never initialized handler you can call Handler handler =getWindow().getDecorView().getHandler();
Upvotes: 0