-1

Suppose I have A class body as:(It is just a rough design of a class.. )

   class XYZ
   {


         //Some Code here
         submitBTN.setOnClickListener(..){
                    ABC obj=new ABC();
                    obj.execute();
                    Toast(obj.result).show();
                 }

         class ABC extends AsynTask<String,Void,String>{
         String result=null;
         ..
         ..
         doInBackground(..){
              ..
              ..
            return "success";

            }
          onPostExecute(String result){
                this.result=result;
               }
    }
    }

My Question is Will Toast Show "Success" or it will show "null"; Since we are starting a another thread in background so obj.execute is a blocking statement or not i mean will the control move to the next statement after .execute statement or will it wait untill the background thread completes?

Johny
  • 1
  • 4
  • No. Impossible. The toast is called before the asynctask runs and certly before it ends. You should put that toast in the onPostExecute() of the AsyncTask. – greenapps Sep 03 '16 at 18:58
  • AsyncTask does not block. The result will be most likely be null – OneCricketeer Sep 03 '16 at 19:03
  • 1
    Possible duplicate of [How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?](http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a) – OneCricketeer Sep 03 '16 at 19:04

2 Answers2

0

The control will move to toast because Asyctask task executes in its own thread. But obj.result will give null result because you there is no guarantee that result will be set before toast execution.

Sangeet Suresh
  • 2,527
  • 1
  • 18
  • 19
0

You can use Interfaces

public interface OnStuffDone{
 void onResult(String result);
 }

public AsyncTask<String,Void,String> abc (OnStuffDone onStuffDone){
   return new AsyncTask<String,Void,String>
       ...
    doInBackground(..){

         ...
        return "success";

        }
      onPostExecute(String result){
            onStuffDone.onResult(result);
           }

       }

      abc(new OnStuffDone
      ...
      @Override
     public void onResult(String result){
     //Show result
     }
    ).execute()
Tiago Oliveira
  • 1,582
  • 1
  • 16
  • 31