Skip to content Skip to sidebar Skip to footer

Android Class With Sub-class Asynctask Wait For The Postexecute Before Returning The Value

currently I'm doing something for my project wherein I created a separate Class that will only handle the Asynctask and get the value of the webservices I passed and that class sho

Solution 1:

Your issue is with usage of this

new UploaderTaskStandard().execute().get();

Although you using AsynTask, but still making system wait until result which is against your requirement, what you need is a delivery mechanism, which will notify you back once results are ready. You can take either of two approaches.

change to this, and implement one of below mechanism.
new UploaderTaskStandard().execute();
  1. Implementing handler, and posting result back once result available.
  2. Implementing observer design pattern, where you create an interface with methods such as onResultReady, and passing an object of class implementing above interface to your method startTask, and posting result back from AsyncTask onPostExecute once it is available via interface mechanism.

Going via interface will be very easy and in this way your code will be independent of your network logic, sample code below

// Observer listener interface designinterfaceResultListener{
    // You can overload this method with data type you want to returnpublicvoidonResultReceived();

    // Use them in a proper way for sending error message back to your programpublicvoidonTaskCancelled();
    publicvoidonError();

}
 // This will be your new method signaturepublic String startTask(ResultListener listener){
     // Call it liske this, passing listener referencenew UploaderTaskStandard().execute(listener);
 }

 // This is your AsyncTask modelpublicclassUploaderTaskStandardextendsAsyncTask<ResultListener, Void, Void> {

     ResultListener listener;

        @Override
        protected Void doInBackground(ResultListener... maps) {
            this.listener = maps[0];
            uploadData();
            returnnull;
        }

        protectedvoidonPostExecute(Void v) {
            /*Do something after the task is complete*/
            simpleDialog.dismiss();
            // Notify back to calling program
            listener.onResultReceived();
        }

 }

Post a Comment for "Android Class With Sub-class Asynctask Wait For The Postexecute Before Returning The Value"