开发者

Android - Problem with AsyncTask

I needs to make a call to a webservice for 5 times(as there are 5 different parameters) one by one o开发者_如何学Cr all at once. Once a particular call completed, in background a textview should be updated with text as: "1st completed", "2nd Completed" and so on.

TextView value should be updated in background.

What should i do ? I am knowing the concept of AsyncTask, but i am confused that should i write 5 AsyncTask and then for each i write execute() method to execute the AsyncTask?

I am successful for only 1 one call, as i set "1st completed" in postExecute() method. But confused for the 5 times call.

Please suggest me a better way or exact solution.


You only need 1 AsyncTask, you have to do all 5 calls in the doInBackground() and everytime you complete one call the publishProgress passing for example the number of the completed call, then, at the end do whatever you need in onPostExecute.

A simple approach:

private class ServiceCallTask extends AsyncTask<String, Integer, Void> {

    protected void onPreExecute() {
        //prepare whatever you need
        myTextField.setText("starting calls");
    }

    protected Void doInBackground(String... params) {
        //process params as you need and make the calls
        doCall1();
        publishProgress(1); //this calls onProgressUpdate(1)
        doCall2();
        publishProgress(2);
        doCall3();
        publishProgress(3);
        doCall4();
        publishProgress(4);
        doCall5();
        publishProgress(5);
        return;
    }

    protected void onProgressUpdate(Integer... progress) {
        //this runs in UI thread so its safe to modify the UI
        myTextField.append("finished call " + progress);
    }

     protected void onPostExecute(Void unused) {
        myTextField.append("all calls finished");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜