korunos
korunos

Reputation: 798

How to cancel doInBackground in AsyncTask

Here is my Code:

class XMLDownload extends AsyncTask<URL, Void, ArrayList<HashMap<String, String>>> {

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(URL... urls) {
        if (cd.isConnectingToInternet()) {
            URL url = urls[0];
            XMLParser xmlParser = new XMLParser();
            String xml = xmlParser.getXMLFromUrl(url);

            Document doc = xmlParser.getDomElement(xml);
            if (doc == null){
                Toast.makeText(context,"Falsche URL",Toast.LENGTH_SHORT).show();                  
            } else {
                writeToFile(xml, "xmlfilesnames" + ".kx_todo");
                [...]
    }

    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> xmlItems) {
        if (cd.isConnectingToInternet()) {
            CustomAdapterProjects adapter = new CustomAdapterProjects(ListViewActivity.context, projectItems);
            setListAdapter(adapter);
        }
    }
}

If the User gives the wrong URL and doc is null. Then i want to show a Toast.

I've read some other Threads about canceling the AsyncTask but this is more unique because i have a NPE INSIDE the doInBackground method and not else where.

How can i cancel the doInBackground method. It makes no sense to continue the method. Otherwise i get a lot of NPE (NullPointerException).

Upvotes: 2

Views: 1049

Answers (3)

Ajay S
Ajay S

Reputation: 48592

How can i cancel the doInBackground method. It makes no sense to continue the method. Otherwise i get a lot of NPE (NullPointerException).

You can cancel your AsyncTask by simply calling xMLDownload.cancel(true);.

Upvotes: 1

Pankaj
Pankaj

Reputation: 8058

Just return null if url or doc any of them is null.

if(doc == null || url == null){
  return null;
}

and then in onPostExceute you can do whatever you want to do.

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157437

if (doc == null) {
  return null;
}

and onPostExecute check if xmlItems is null. If it is null show the Toast

Upvotes: 3

Related Questions