0

I have an AsyncTask that is called by a group of methods something like this:

makeCall1();
makeCall2();
makeCall3();
makeCall4();
makeCall5();

problem being each has a "status message" that needs to display while they run. Since I have them running like I do above they all run together and the "status message" does one massive change. What I'd like is to have it step through each call and only make the next one once the first AsyncTask is complete.

My Async is done like below:

public class JSONParser extends AsyncTask<String, String, JSONObject> {

        InputStream is = null;
        JSONObject json = null;
        String outPut = "";
        protected void onPreExecute(String f){

        }

        @Override
        protected JSONObject doInBackground(String... params) {
            // TODO Auto-generated method stub
            ...
            publishProgress(params[3]);
            ...

            return json;
        }

        protected void onProgressUpdate(String...values) {
            statusMessage.setText(values[0]);
         }

        protected void onPostExecute(JSONObject result) {

        }
    }

What is the best way to make each call one at a time?

----- EDIT -----

Additional code as requested

I've changed the names of things below and placed "...." where pieces of code aren't really relevant such when it saves to the database:

public class SplashScreen extends Activity {

     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        statusMessage = (TextView) findViewById(R.id.statusMessage);
    }

    protected void onResume(){
        super.onStart();
        if(isNetworkAvailable()){
            statusMessage.setText("Connection Found");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    final String appUpdateDate = null;
                    getAPI1(appUpdateDate);
                    getAPI2(appUpdateDate);
                    getAPI3(appUpdateDate);
                    getAPI4(appUpdateDate);
                    getAPI5(appUpdateDate);
                    getAPI6(appUpdateDate);

                    endSplash();
                }

            }, SPLASH_TIME_OUT);
        }
        else {
            statusMessage.setText("No Connection Found");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    endSplash();
                }

            }, SPLASH_TIME_OUT);
        }

    }

    public void endSplash(){

        ....
        goes to main activity after timeout
        ....

    }

     private boolean isNetworkAvailable() {
        ....
        checks for internet connection
        ....
    }

    //this is an example of getAPI1. There are 5 more but each do a different database and api call. The AsyncTask is what does the api call and parses the json it returns.
    public void getAPI1(String appUpdateDate){
        String URL = "http://API_URL";
        String requestType = "X";
        String getType = "Y";
        URL = URL+requestType+"/"+getType;
        SQLiteDatabase database = APIDB.getWritableDatabase();
        try {
            JSONObject output = new JSONParser().execute(new String[] {URL,consumerKey,sharedSecret,"Updating X"}).get();
            JSONArray jsonx = output.getJSONArray("Data");

            ....
                        runs through jsonX and saves data to database
                        ....


        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public class JSONParser extends AsyncTask<String, String, JSONObject> {

        InputStream is = null;
        JSONObject json = null;
        String outPut = "";
        protected void onPreExecute(String f){

        }

        @Override
        protected JSONObject doInBackground(String... params) {
            // TODO Auto-generated method stub
            publishProgress(params[3]);
            String url = params[0];
            String ck = params[1];
            String ss = params[2];
            Log.d("url",url);
            Log.d("ck",ck);
            Log.d("ck",ss);
            List<NameValuePair> values = new ArrayList<NameValuePair>();
            values.add(new BasicNameValuePair("ConsumerKey", ck));
            values.add(new BasicNameValuePair("SharedSecret", ss));
            try {

                ....
                        get the json from the api
                        ....

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            ....
                parse the json to be returned
                ....

            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            try {
                json = new JSONObject(outPut);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            // return JSON String

            return json;
        }

        protected void onProgressUpdate(String...values) {
            statusMessage.setText(values[0]);
         }

        protected void onPostExecute(JSONObject result) {
        }
    }

}
5
  • Why do you hate my interface suggestion?
    – codeMagic
    Jan 13, 2014 at 23:07
  • I thought the same thing as shown below.
    – horvste
    Jan 13, 2014 at 23:07
  • Honestly?... Because I have having difficulty understanding it. I've had to do an extraordinary amount of crash course Android in 2 months. So, if I'm being honest, I just don't follow the solution very well.
    – dcp3450
    Jan 13, 2014 at 23:13
  • See real world example below dcp3450
    – horvste
    Jan 13, 2014 at 23:14
  • not that it matters... but do you have any idea how hard it is to do this while someone is practicing trumpet next to you?
    – dcp3450
    Jan 13, 2014 at 23:22

3 Answers 3

2

Starting from API level 11 / Honeycomb, the default asynctask executor is SERIAL_EXECUTOR so individual asynctasks are already executed serially, unless you explicitly specify e.g. THREAD_POOL_EXECUTOR. So, provided that both your minimum and target SDK versions are 11 or above, just execute() your asynctasks and they'll be run as soon as the executor is available.

To deal with UI updates such as status messages, use onPreExecute(), onProgressUpdate() and/or onPostExecute(). If you need to pass in additional parameters to the async task, you can give them in constructor args and store in member variables.

4
  • onPreExecute() doesn't get any of the parameters passed to it so I can't send unique updated text per call.
    – dcp3450
    Jan 13, 2014 at 23:01
  • I've placed the updated text in all three places and it waits till they all run before it changes anything since they all run together.
    – dcp3450
    Jan 13, 2014 at 23:16
  • targetSdkVersion is 19
    – dcp3450
    Jan 13, 2014 at 23:21
  • Same thing as this suggestion (let the system handle this for you), you could use an IntentService, which does the same thing (executes serially).
    – Booger
    Jan 13, 2014 at 23:22
1
public class JSONParser extends AsyncTask<String, String, JSONObject> {
OnFinished onFinished;

JsonParser(OnFinished onFinishedWithTask) {
    this.onFinished = onFinishedWithTask;
}

InputStream is = null;
JSONObject json = null;
String outPut = "";

protected void onPreExecute(String f) {

}

@Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        ...
        publishProgress(params[3]);
        ...

        return json;
    }

protected void onProgressUpdate(String... values) {
    statusMessage.setText(values[0]);
}

protected void onPostExecute(JSONObject result) {
    this.onFinished.onFinishedWithTask();

}

}

public interface OnFinished {
    public void onFinishedWithTask();
}

Something like this may work for you.

Then call the first one and when its done call the second one and so on...If you need to update the ui in 'onprogressupdate' just make another method in the interface and call it.

Heres a larger example to give you an overview of how one could go about this:

public class DownloadWebPage extends AsyncTask<String, Integer, StringBuilder> {
    private OnProgressUpdate updateInter;
    private String url;

    public DownloadWebPage() {
        super();
    }

    public DownloadWebPage(OnProgressUpdate updateInter) {
        this.updateInter = updateInter;
    }

    public DownloadWebPage(OnProgressUpdate updateInter, String url) {
        this(updateInter);
        this.url = url;
    }

    @Override
    protected StringBuilder doInBackground(String... url) {
        System.out.println("start downloading");
        try {
            System.out.println("url 0 =" + url[0]);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url[0]);
            HttpResponse response = client.execute(request);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            long content = response.getEntity().getContentLength();
            String line = "";
            StringBuilder htmlBuilder = new StringBuilder();
            long bytesRead = 0;
            while ((line = rd.readLine()) != null) {
                htmlBuilder.append(line);
                bytesRead = bytesRead + line.getBytes().length + 2;
                publishProgress(new Integer[] { (int) (((double) bytesRead / (double) content) * 100) });
            }
            System.out.println("end downloading");
            return htmlBuilder;
        } catch (IOException e) {
            System.out.println(e.toString());
            return null;
        }

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        if (values[0].equals(Math.abs(values[0]))) {
            updateInter.onUpdate(values[0]);
        } else if (!values[0].equals(Math.abs(values[0]))) {
            updateInter.onUpdateFailure();
        }
    }

    @Override
    protected void onPostExecute(StringBuilder result) {
        if (result == null) {
            updateInter.onFailure();
        } else if (result != null) {
            updateInter.onSuccess(result);
        }

    }

    public void setOnProgressUpdate(OnProgressUpdate updateInter) {
        this.updateInter = updateInter;

    }

    public void downloadHtml() {
        if (url == null) {
            updateInter.onFailure();
            return;
        }
        System.out.println("STATUS=" + getStatus());
        if (getStatus().equals(AsyncTask.Status.FINISHED)) {
            DownloadWebPage iseDownloader = new DownloadWebPage();
            iseDownloader.setOnProgressUpdate(updateInter);
            iseDownloader.execute(new String[] { url });
        } else if (getStatus().equals(AsyncTask.Status.RUNNING)) {
        } else {
            execute(new String[] { url });
        }
    }

    public void downloadHtml(String urlToDownload) {
        this.url = urlToDownload;
        downloadHtml();
    }
}

Heres the interface:

   public interface OnProgressUpdate {
    public void onUpdate(Integer percentProgress);

    public void onUpdateFailure();

    public void onSuccess(StringBuilder result);

    public void onFailure();

}

Heres usage:

public final class OnProgressUpdater implements OnProgressUpdate {
        private final FortschoolsFragment fortSchoolsFragment;
        private final SchoolActivity a;

        public OnProgressUpdater(SherlockFragment fragment, Activity a) {
            this.fortSchoolsFragment = (FortschoolsFragment) fragment;
            this.a = (SchoolActivity) a;
            this.a.startRefreshing();
            this.a.disableSpinner();
        }

        @Override
        public void onUpdate(Integer percentProgress) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onUpdateFailure() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess(StringBuilder result) {
            final Document doc = Jsoup.parse(result.toString());
            final Site site = new FortSchoolSite(doc);
            dataList = site.getNews();
            if (JavaUtility.isNull(fortSchoolsFragment.getSherlockActivity())) {
                return;
            }
            mListViewAdapter = new DataAdapter(fortSchoolsFragment
                    .getSherlockActivity().getApplicationContext(), dataList);
            mListView.setAdapter(mListViewAdapter);
            this.a.stopRefreshing();
            this.a.enableSpinner();

        }

        @Override
        public void onFailure() {
            this.a.stopRefreshing();
            this.a.enableSpinner();
            Toast.makeText(a.getApplicationContext(), "Something Went Wrong",
                    Toast.LENGTH_LONG).show();

        }

    }

Now OnProgressUpdater is called with this:

DownloadWebPage page = new DownloadWebPage(new OnProgressUpdater(this,
                getSherlockActivity()), this.mSchool.getSchoolUrl());

page.downloadHtml();

We are making are own OnClickListener in a way.

Back to your example. We would only start another asynchtask when your onFinishedWithTask(); method of the interface is called.

Another option is to skip the *AsynchTask* and use traditional java threading. You would make a private inner class which implements Runnable and then do your work inside the run(); method and update the ui through the runOnUiThread method.

Example of skipping asynchtask:

protected class SdfaOverviewThread implements Runnable {
        private static final String SOMEURL = "SOMEURLGOESHERE";

        @Override
        public void run() {
                   //not proper but does illustrate point
            Document doc = Jsoup.connect(SOMEURL).get();
            final Document runOnUiDoc = doc;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
/* Html parsing is just an example showing what one could do.
 * Do not worry about fragment details either they are just illustrating a point*/ 
                    SdfaOverviewFragment sdfaOverviewFrag = ((SdfaOverviewFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.FrameLayout1));
                    String theme = runOnUiDoc.select("head").select("style")
                            .get(1).toString();
                    String upcomingEvents = runOnUiDoc.select(
                            "div#sw-innerWrap2").toString();
                    String news = runOnUiDoc.select("div#sw-newsContainer")
                            .toString();
                    String quickLinks = runOnUiDoc.select("div.sw-column")
                            .toString();
                    String html = theme + upcomingEvents; //+ news + quickLinks;
                    sdfaOverviewFrag.getWebView().loadDataWithBaseURL(
                            SOMEURL, html, "text/html", "UTF-8",
                            SOMEURL);

                }
            });
            Log.d(TAG, "Finished Running Thread");
        }
    }

Now we execute with:

Thread thread = new Thread(new SdfaOverviewThread());
    thread.start();

Skipping the Asynchtask could also apply to your situation as well.

Just to recap, you could:

  1. Use an interface in the asynchtask and have classes that want to use those methods: create an anonymous class or private inner class which implements the interface.
  2. Skip the asynchtask and use traditional java threading.

Use whichever method you feel creates the most maintainable code.

EDIT I can only give you examples; consider posting more code.

public class JSONParser extends AsyncTask<String, String, JSONObject> {
    private OnFinished onFinished;

    public JSONParser(OnFinished onFinished) {
        this.onFinished = onFinished;
    }

    @Override
    protected JSONObject doInBackground(String... arg0) {
        JSONObject object = new JSONObject();
        // get data from arg0
        return object;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        onFinished.onProgressUpdate(Integer.parseInt(values[0]));
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        onFinished.onFinishedWithTask(result);
    }
}

public interface OnFinished {
    public void onProgressUpdate(Integer percentProgress);

    public void onFinishedWithTask(JSONObject object);
}
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Stack<String> data = new Stack<String>();
        data.push("jsonData");
        data.push("jsonData");
        data.push("jsonData");
        data.push("jsonData");
        data.push("jsonData");
        JSONParser parser = new JSONParser(new Parser(data));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class Parser implements OnFinished {
        private Stack<String> stack;

        public Parser(Stack<String> stack) {
            this.stack = stack;
        }

        @Override
        public void onProgressUpdate(Integer percentProgress) {
            // update ui from percent progress;

        }

        @Override
        public void onFinishedWithTask(JSONObject object) {

            // if their are no more objects left we will do nothing or else we
            // will create a new Asynchtask
            if (stack.isEmpty()) {
                return;
            }
            new JSONParser(this).execute(stack.pop());

        }

    }

}

The basic idea is that when onFinishedTask(JsonObject obj) is called you will update the userinterface from the JsonObject obj and then start a new asynchtask until you run out of the data.

Do something similar to this (you only instantiate this one time):

   public class JSONParser extends AsyncTask<String, String, JSONObject> {

        InputStream is = null;
        JSONObject json = null;
        String outPut = "";
        private int api;
        public JSONParser(int api) {
        this.api= api;
        }

        protected void onPreExecute(String f){

        }

        @Override
        protected JSONObject doInBackground(String... params) {
            String appUpdateDate = params[0];
            String url = null;
            String ck = null;
            String ss = null;
            String updating = null;
            switch(api){
            case
            11:
                String URL = "http://API_URL";
            String requestType = "X";
            String getType = "Y";
            URL = URL+requestType+"/"+getType;
            SQLiteDatabase database = APIDB.getWritableDatabase();
            /*
             * Write to vars url ck ss updating
             */

                break;
            }




            Log.d("url",url);
            Log.d("ck",ck);
            Log.d("ck",ss);
            List<NameValuePair> values = new ArrayList<NameValuePair>();
            values.add(new BasicNameValuePair("ConsumerKey", ck));
            values.add(new BasicNameValuePair("SharedSecret", ss));
            try {

                ....
                        get the json from the api
                        ....

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            ....
                parse the json to be returned
                ....

            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            try {
                json = new JSONObject(outPut);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            // return JSON String

            return json;
        }

        protected void onProgressUpdate(String...values) {
            statusMessage.setText(values[0]);
         }

        protected void onPostExecute(JSONObject result) {
            /*
             * Do something to update ui with result
             */
            api++;
            if(api >  6){
                return;
            }
            new JSONParser(api).execute("insert data here");
    }
12
  • This is a great answer that will take time for me to decipher... lol
    – dcp3450
    Jan 13, 2014 at 23:29
  • depending on how fast these tasks complete, you might want to add a timeout to the onFinishedWithTask execution, so the user can actually read the information, unless speed takes priority, in which case you should just be logging the output and allow it to be re-read later.
    – Dani
    Jan 13, 2014 at 23:30
  • @horvste - I'll go over this in detail and comment back if/when I hit issues. It might take me a bit.
    – dcp3450
    Jan 13, 2014 at 23:56
  • I can't figure out how to relate this to my situation. I'm not saying it's not the answer... I just can't relate the solution to running multiple calls the AsyncTask one at a time.
    – dcp3450
    Jan 14, 2014 at 6:33
  • @dcp3450 You will call the other AsynchTask(s) in the onFinishedWithTask(); Will modify more later
    – horvste
    Jan 14, 2014 at 14:44
0

since these methods don't take any variables, why not just have a call back in each function with a timeout to the next function and piggy back them?

2
  • in reality it's more like makeCall1(date); -> makeCall(String date) makes the AsyncTask call that parses JSON and uses the response to input content to the database.
    – dcp3450
    Jan 13, 2014 at 23:28
  • ah, gotcha, well horvste is doing what I was thinking in a much more elegant way. go with his solution ;)
    – Dani
    Jan 13, 2014 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.