Danny Ho
Danny Ho

Reputation: 149

Async in a Async task

I put the following code in the doInBackground() in another AsyncTask which this HttpPostHandler contain another AsyncTask. Then the handler.get() just keep loading.
Anyone got any idea about this?
Is this the problem about the threads???

Code:

@Override
    protected Void doInBackground(Void... params) {
        try {
                champ = Utility.getCounter("test");

                this.wait(3);
                }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

In Utility:

public static int getCounter(String code) {
    HttpPostHandler handler = new HttpPostHandler();
    try {
        handler.execute(counter_URL + code);
        handler.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    String html = handler.getResultJSONString();
    TagNode tagNode;

    ...
}

The following is the HttpPostHandler AsyncTask

    public class HttpPostHandler extends AsyncTask<String, Void, String> {

        private String url;
        private String resultJSONString=null;
        private JSONObject resultJSON;

        public String getResultJSONString() {
            return resultJSONString;
        }

        public void setResultJSONString(String resultJSONString) {
            this.resultJSONString = resultJSONString;
        }

        private static String toUTF8(InputStream is){
            //InputStream is = resEntity.getContent();
            InputStreamReader isr = null;
            StringBuffer buffer = new StringBuffer();
            try {
                isr = new InputStreamReader(is, "utf-8");
                Reader in = new BufferedReader(isr);
                int ch;
                while((ch = in.read()) != -1){
                    buffer.append((char)ch);
                }
                isr.close();
                is.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            }
            return buffer.toString();
        }

        @Override
        protected String doInBackground(String... params) {
                String result = "";
                DefaultHttpClient client = new DefaultHttpClient();
                try {
                    HttpGet get = new HttpGet(params[0]);
                    HttpResponse response = client.execute(get); 
                    Log.d("danny", "response = "+response);
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = toUTF8(resEntity.getContent());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    client.getConnectionManager().shutdown();
                }
                setResultJSONString(result);
                return result;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            resultJSONString = result;
        }
    }

Upvotes: 0

Views: 168

Answers (3)

Macrosoft-Dev
Macrosoft-Dev

Reputation: 2185

Here is an example of publish progress:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

}

please voteup or mark true if it is helpful for you.

Upvotes: 1

Macrosoft-Dev
Macrosoft-Dev

Reputation: 2185

Use publish progress method of asynctask class in doinbackground() instead of direct call "handler.execute".

Call "handler.execute" in onprogressupdate() and call publish progress in doInBackground.

Upvotes: 1

Pheel125
Pheel125

Reputation: 113

If you are running in API 11 (3.0) or later, you can change your handler.execute(counter_URL + code); to handler.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, counter_URL + code);

This allows for multiple AsyncTasks to be run simultaneously.

Upvotes: 1

Related Questions