Search code examples
androidandroid-activityandroid-asynctaskexecution

Code in AsyncTask isn't executing


I have an AsyncTask which is executed just before my application quits. It gets the location and also parses my layout xml file. The location is retrieved but the parsing doesn't get executed.

Calling AsyncTask in my Main Activity:

public void quitApplication()
    {       
        FinishProcess fProcess = new FinishProcess();
        fProcess.execute(this);
}

AsyncTask:

public class FinishProcess extends AsyncTask<Main, Void, Void>
{
    @Override
    protected Void doInBackground(Main... params) {
        LocationHandler lh = new LocationHandler();
        try {
            lh.getLocationSingle(null, params[0]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        parseXML(params[0]);
        return null;
    }

    private void parseXML(Main params)
    {
        String ANDROID_ID = "android:id";       
        Resources resources = params.getResources();

        try {
            InputStream fXmlFile = resources.openRawResource(R.raw.pages);

            //Reads xml file and gets the node types and attributes
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("*");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);   
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println(eElement.getNodeName());
                }
            }

        } 
        catch (Exception e) {
            System.out.println("Catch");
            e.printStackTrace();
        }

    }


}

Solution

  • If your application is quitting after starting this process, then perhaps the main thread is dying while the background one (AsyncTask) is running, thereby orphaning it. If this needs to be done during shutdown try doing it in Application.onTerminate without the AsyncTask thread.