0

I am trying to stop my AsyncTask when the app exits, but I get the following exception. Where am I wrong? this is my code -

I declare the variable-

private DownloadFileAsync mTask;

then in onDestroy-

@Override
public void onDestroy() {
    Log.v("SERVICE", "Service killed");
    mTask.cancel(true);
    super.onDestroy();
}

03-03 08:57:41.200: E/AndroidRuntime(22678): java.lang.RuntimeException: Unable to stop service com.exe.shark.NSOMUHBroadcastService@d58223c: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.exe.shark.NSOMUHBroadcastService$DownloadFileAsync.cancel(boolean)' on a null object reference

Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40
  • `mTask` is null. refer this http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – arjun Mar 03 '17 at 14:04
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Atef Hares Mar 03 '17 at 14:06

3 Answers3

0

try checking if mTask in not null

@Override
public void onDestroy() {
    Log.v("SERVICE", "Service killed");
    if(mTask != null) {
        mTask.cancel(true);
    }
    super.onDestroy();
}
0

It's possible your AsyncTask has not been instantiated or run by the time your Activity is being destroyed. So you might have to check that mTask is not null.

You might also want to check if mTask is still running at the time the Activity is being destroyed by calling mTask.getStatus() == AsyncTask.Status.RUNNING .

TrueKojo
  • 106
  • 2
  • 6
0

It looks like mTask is not being set and is null. To start an AsyncTask do something like the following:

DownloadFileAsync mTask = new DownloadFileAsync (...parameters vary...);
mTask.execute(...parameters vary...);

It is not enough to just declare the task variable - you must explicitly start it as shown above. See the documentation for details.

I will also mention here that mTask.cancel(true) will not actually cancel your task unless you check for the cancel flag within the task and exit gracefully, but that is something you will have to program. See "Cancelling a task" is the referenced documentation above.

Cheticamp
  • 61,413
  • 10
  • 78
  • 131