I am implementing AsyncTask for my understanding of concepts. The code is working but not in way I want to. I have gone through the documents but cannot pin point what wrong am I doing.
Code:
private class NewThread extends AsyncTask<Integer, Integer , String>
{
@Override
protected String doInBackground(Integer... params) {
Log.d(TAG,"inside doInBackground");
for (int i=0;i<params.length;i++)
{
try {
publishProgress(i);
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Finished";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.d(TAG,"inside onPostExecute");
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(getBaseContext(), "Done " + values[0], Toast.LENGTH_SHORT).show();
Log.d(TAG,"inside onProgressUpdate");
}
I only see Done 0 and Finished. What I was expecting is Done0 , Finished, Done1, Finished, Done2. Finished…. OR Done0 Done1 Done2 ….Finished.
What should I change in code to do that? Is it even possible?
I am calling AsyncTask using a button.
public void onClick(View v) {
// TODO Auto-generated method stub
new NewThread().execute(4);
}
Thanks
The code you use to start the
AsyncTaskstarts 1 (one) instance, passing4as a parameter. Therefore,param.length()is 1 (one) and you get only one output.Try this instead:
Or maybe this, if you want to see several threads working simultaneously: