So I have a Thread 'ThreadDemo' in a Fragment which does some calculations and uses getActivity().runOnUiThread() to update a TextView. It works fine but when I exit the application, it gives NPE on getActivity(). From what I know about threads in android, they should be stopped when Activity is destroyed but here, for some reason, it continues and is unable to find the activity as i have closed it. Here is my Thread code inside my Fragment-
public class ThreadDemo implements Runnable {
int hour, minute, second, day=0;
public void run() {
while((196-day)>=0) {
Calendar cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_YEAR);
hour = cal.get(Calendar.HOUR_OF_DAY);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
try {
**NPE here** getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
....
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
and here is the LogCat-
06-07 12:05:28.903: E/AndroidRuntime(19834): FATAL EXCEPTION: Thread-5858
06-07 12:05:28.903: E/AndroidRuntime(19834): java.lang.NullPointerException
06-07 12:05:28.903: E/AndroidRuntime(19834): at com.example.mapsapiv2demo.Fragment3$ThreadDemo.run(Fragment3.java:59)
06-07 12:05:28.903: E/AndroidRuntime(19834): at java.lang.Thread.run(Thread.java:856)
NOTE: I tried to manually stop the thread in onPause method but it seems like stop() method is deprecated for threads and is not recommended. Know what I'm doing wrong or any suggestions for a workaround? I'm aware of something like asynctask but I'm a beginner so I would like to avoid that for now. Thanks for your help.