Skip to content Skip to sidebar Skip to footer

Android's Asynctask: Multiple Params, Returning Values, Waiting

I have been looking at how to implement Android's AsyncTask class for some time now. Basically, I want it to do the classic scenario: simply animate an indefinite loading wheel whi

Solution 1:

doStuff(result); this shouldn't execute until the AsyncTask is done

then you will need to use AsyncTask.get() which make Waits if necessary for the computation to complete, and then retrieves its result.

because calling of AsyncTask.get() freeze main UI thread until doInBackground execution is not complete then u will need to use Thread to avoid freezing of UI and runOnUiThread for updating Ui elements after AsyncTask execution complete.

Example :-

publicvoidThreaddoStuff(){

 Thread th=new Thread(){
    @Override
    publicvoidrun(){
      // start AsyncTask exection here
      String result = new PostToFile("function_name", 
                      keysAndValues).execute().get().getResult();

     // now call doStuff by passing result
     doStuff(result);
    }
  };
th.start();
}

Solution 2:

Make a reusable async task with default onPostExecute implementation and then override default implementation for every call:

publicstaticclassPostToFileextendsAsyncTask<Void, Void, String> {
        privateString functionName;
        privateArrayList<NameValuePair> postKeyValuePairs;
        privateString result = "";

        publicPostToFile(Stringfunction, ArrayList<NameValuePair> keyValuePairs){
            functionName= function;
            postKeyValuePairs = keyValuePairs;
        }

        @OverrideprotectedvoidonPreExecute() {
            super.onPreExecute();
            // show progress bar
        }

        @OverrideprotectedStringdoInBackground(Void... arg0) {
            // make request and get the resultreturnnull; // return result
        }

        @OverrideprotectedvoidonCancelled(String result) {
            super.onCancelled(result);
            // hide progress bar
        }

        @OverrideprotectedvoidonPostExecute(String result) {
            super.onPostExecute(result);
            // hide progress bar
        }
    }

Execute your async task:

new PostToFile(function, keyValuePairs) {

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result); // this will hide a progress bardoStuff(result); 
        }
}.execute();

new PostToFile(otherFunction, otherKeyValuePairs) {

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result); // this will hide a progress bardoOtherStuff(result); 
        }
}.execute();

Post a Comment for "Android's Asynctask: Multiple Params, Returning Values, Waiting"