Search code examples
androidandroid-asynctasknetworkonmainthread

Calling another AsyncTask from onPostExecute method


I want to call a new AsyncTask from onPostExecute of the currently finished AsyncTask.

          protected void onPostExecute(Integer feed) {
        dialog1.dismiss();          
        super.onPostExecute(feed);
        new SendsequenceofRequest().execute();
    } 

But I'm receiving following exception:

        android.os.NetworkOnMainThreadException

My logcat output is:

09-30 16:08:19.517: W/System.err(3706): android.os.NetworkOnMainThreadException
09-30 16:08:19.517: W/System.err(3706):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
09-30 16:08:19.517: W/System.err(3706):     at dalvik.system.BlockGuard$WrappedNetworkSystem.read(BlockGuard.java:279)
09-30 16:08:19.517: W/System.err(3706):     at org.apache.harmony.luni.net.PlainSocketImpl.read(PlainSocketImpl.java:448)
09-30 16:08:19.517: W/System.err(3706):     at org.apache.harmony.luni.net.SocketInputStream.read(SocketInputStream.java:75)
09-30 16:08:19.517: W/System.err(3706):     at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
09-30 16:08:19.517: W/System.err(3706):     at org.apache.http.impl.io.SocketInputBuffer.isStale(SocketInputBuffer.java:132)
09-30 16:08:19.517: W/System.err(3706):     at org.apache.http.impl.AbstractHttpClientConnection.isStale(AbstractHttpClientConnection.java:205)
09-30 16:08:19.517: W/System.err(3706):     at org.apache.http.impl.conn.AbstractClientConnAdapter.isStale(AbstractClientConnAdapter.java:185)
09-30 16:08:19.577: W/System.err(3706):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:336)
09-30 16:08:19.577: W/System.err(3706):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-30 16:08:19.577: W/System.err(3706):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-30 16:08:19.597: W/System.err(3706):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-30 16:08:19.597: W/System.err(3706):     at com.dm.ekot.reqres.SimpleHttpClient.sendresponseSequReqRes(SimpleHttpClient.java:715)
09-30 16:08:19.607: W/System.err(3706):     at com.dm.ekot.MainScreen$SendsequenceofRequest$1$1.run(MainScreen.java:1020)
09-30 16:08:19.620: W/System.err(3706):     at android.os.Handler.handleCallback(Handler.java:587)
09-30 16:08:19.620: W/System.err(3706):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-30 16:08:19.620: W/System.err(3706):     at android.os.Looper.loop(Looper.java:132)
09-30 16:08:19.620: W/System.err(3706):     at android.app.ActivityThread.main(ActivityThread.java:4025)
09-30 16:08:19.627: W/System.err(3706):     at java.lang.reflect.Method.invokeNative(Native Method)
09-30 16:08:19.627: W/System.err(3706):     at java.lang.reflect.Method.invoke(Method.java:491)
09-30 16:08:19.627: W/System.err(3706):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
09-30 16:08:19.627: W/System.err(3706):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
09-30 16:08:19.642: W/System.err(3706):     at dalvik.system.NativeStart.main(Native Method)

In my SendsequenceofRequest AsyncTask I do start another thread in doInBackground() method.

            class SendsequenceofRequest extends AsyncTask<String, Void, Integer> {

//  private ProgressDialog dialog1;

    protected void onPreExecute() {
    //  dialog1 = ProgressDialog.show(MainScreen.this, "", "Loading...");   
    }   

    protected void onPostExecute(Integer feed) {
    //  dialog1.dismiss();          
        super.onPostExecute(feed);
    }        

    @Override
    protected Integer doInBackground(String... arg0) {    

                   String  str_stater_menu = "Starters";
                   String response_starter = "";
                try {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            while (isThreadPaused1) {
                                try {
                                    Thread.sleep(3000);
                                    mHandler.post(new Runnable() {    

                                        @Override
                                        public void run() {
                                            // TODO Auto-generated method stub   
                                            try {
                                                final String response_req_sequence = SimpleHttpClient.sendresponseSequReqRes(response_send_order);
                                                System.out.println(" i  ma in thread");
                                                if(response_req_sequence != null)
    {
                                                     onPause();
         runOnUiThread(new Runnable() {    
                @Override  
                public void run() {    
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), "Your Order will be delivered in"+response_req_sequence, 10000).show();
                }
            });
    }
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
                                        }
                                    });
                                } catch (Exception e) {  
                                    // TODO: handle exception
                                }
                            }
                        }
                    }).start();
                    //response_starter = SimpleHttpClient.sendFirstStarter(str_stater_menu);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }    
                   System.out.println("i am getting response for starter"+response_starter);
                // str_reponse_request_tableid_ip = SimpleHttpClient.sendIpTabletId(url , str_ip);

               /** 
                *      
                */
                //  res = response_starter.toString();
                  System.out.println("response TEST: "+res);
            //   Object obj = response_starter.toString();
               System.out.println("after object creation ");

              // getJsonStringForStarter(response_starter);

               System.out.println("response :"+res);       

           /** Inside the new thread we cannot update the main thread
           So updating the main thread outside the new thread */
           try {   

           }catch (Exception e) {  
        e.printStackTrace();  
              // e.printStackTrace();
           }
        return null;
           }       


    }

When i go through several link i couldn't found any help as my issue. So please nay body help me to take me out of this issue. Thanks in advance to all.


Solution

  • I would suggest the use of publishProgress to publish the current progress and override onProgressUpdate which is executed on the main thread. With that, you won't have to use handlers and Threads in the AsyncTask at all.

    Notice that the first line has changed from extends AsyncTask<String, Void, Integer> to extends AsyncTask<String, String, Integer>. The middle parameter determines the object type of the Update Parameter. If you need to send complex data to the update method, change it to a class containing all information necessary.

    class SendsequenceofRequest extends AsyncTask<String, String, Integer> {
        @Override
        protected Integer doInBackground(String... arg0) {    
            try {
                // This will run indefinitely, unless stopped by break. So make sure you have an exit condition, see below
                String response_req_sequence = null;
                do {
                    response_req_sequence = SimpleHttpClient.sendresponseSequReqRes(response_send_order);
                    if(response_req_sequence != null) {
                        // Instead of calling runOnUiThread, call progress update
                        publishProgress(response_req_sequence);
                    }
    
                    // Wait before retry
                    Thread.sleep(3000);
    
                // Keep in mind, that if the connection is successful, the string may be empty,
                // so TextUtils.isEmpty(response_req_sequence); may be better exit condition as it checks if string is null or has size of 0
                } while(response_req_sequence!=null);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        @Override
        void onProgressUpdate(String... string) {
            // This will always be executed in main thread
            onPause();
            Toast.makeText(getApplicationContext(), "Your Order will be delivered in"+response_req_sequence, 10000).show();
        }
    
        protected void onPostExecute(Integer feed) {
            // Notify user the task has bene completed
            Toast.makeText(getApplicationContext(), "Task completed.", 10000).show();
        }        
    }