Sunday, May 6, 2012

Async Task in Android


Here in asynctask, there are some overrided functions,
1. doInBackground
2. onPreExecute(execute before doInBackground)
3. onPostExecute(execute after doInBackground)
4. onProgressUpdate(doInBackground can call this function while its executing using  'publishProgress(integer value)'. Mainly for showing progress bar while downloading or uploading something)

private class SyncIncoData extends AsyncTask<String, String, String> {
ProgressBar pb;
ProgressBar pbar;

@Override
protected String doInBackground(String... urls) {
for (int i = 0; i <= 100; i++) {
publishProgress(i);
}
return null;
}

@Override
protected void onPreExecute() {

super.onPreExecute();

pb = (ProgressBar) findViewById(R.id.progressBarsync4);
pb.setVisibility(View.VISIBLE);

}

@Override
protected void onPostExecute(String result) {

pb = (ProgressBar) findViewById(R.id.progressBarsync4);
pb.setVisibility(View.INVISIBLE);

}

@Override
protected void onProgressUpdate(String... values) {
pbar = (ProgressBar) findViewById(R.id.progressBarpbar);
pbar.setProgress(Integer.parseInt(values[0]));
super.onProgressUpdate(values);
}
}


For calling async task,
SyncIncoData task = new SyncIncoData();
task.execute(new String[] { null });