cmcowart
cmcowart

Reputation: 193

AsyncTask never executing doInBackground (but does in debug) (Update: Fixed)

Fixed: Turns out the problem was that I was clearing the ArrayList after passing it in to the Task, so by the time it got around to executing it, there was nothing there to send. It was working in debug because it could execute before I let it step to the next line. Lesson learned: dont pass in variables that are reused for long running tasks :) Thanks to those of you who answered.

I'm trying to have user selection data sent to my webserver using an async task. Typically the user will make a selection and a string of 3 or 4 commands are sent to an AsyncTask to handle this. When I run the code, the AsyncTask is being created, but never executing the doInBackground method. Even more peculiar is that when I run in debug mode and have it step through the task creation, it works perfectly.

private class SendCommandTask extends AsyncTask< ArrayList<Command>, Void, String>{

        protected String doInBackground(ArrayList<Command>... requests){
            conn = null;
            ArrayList<Command> values = requests[0];

            for( int i = 0; i < values.size(); i++){
                try {
                    url = new URL( siteRoot + values.get(i).getEndPoint() );
                    conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Cookie", authCookie);
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setDoOutput(true);

                    OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
                    os.write(values.get(i).getJson().toString());
                    os.flush();                     
                }catch (IOException e) {
                    e.printStackTrace();
                }
                finally{
                    conn.disconnect();              
                }
            }
            return null;
        }
    }

which is called from the UI thread via the following method:

public void sendCommand(ArrayList<Command> commands){
        new SendCommandTask().execute(commands);
    }

I've looked at similar threads but they just suggest using a different method, which I would rather not do since this seems to be working (in debug :( )

Upvotes: 2

Views: 2401

Answers (1)

P Varga
P Varga

Reputation: 20249

If it seems to not be executing, something might be throwing an Exception in doInBackground, in which case the LogCat will have a stacktrace from the background thread (maybe something like siteRoot is null?)

Upvotes: 2

Related Questions