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 :-

public void  ThreaddoStuff(){

 Thread th=new Thread(){
    @Override
    public void run(){
      // 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:

public static class PostToFile extends AsyncTask<Void, Void, String> {
        private String functionName;
        private ArrayList<NameValuePair> postKeyValuePairs;
        private String result = "";

        public PostToFile(String function, ArrayList<NameValuePair> keyValuePairs){
            functionName= function;
            postKeyValuePairs = keyValuePairs;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // show progress bar
        }

        @Override
        protected String doInBackground(Void... arg0) {
            // make request and get the result
            return null; // return result
        }

        @Override
        protected void onCancelled(String result) {
            super.onCancelled(result);
            // hide progress bar
        }

        @Override
        protected void onPostExecute(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 bar

            doStuff(result); 
        }
}.execute();

new PostToFile(otherFunction, otherKeyValuePairs) {

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

            doOtherStuff(result); 
        }
}.execute();

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