I have a conceptual problem related to AsyncTask
class. We use AsyncTask
so that the main UI is not blocked.
But suppose, I want to retrieve some data
When an asynchronous task is executed, the task goes through 4 steps:
1.onPreExecute(), invoked on the UI thread before the task is executed. use this to diaply progress dialog.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. Can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). Used to publish progress.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
In your activity onCreate()
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView)findViewById(R.id.textView);
new TheTask().execute();
}
class TheTask extends AsyncTask {
protected void onPreExecute() {
//dispaly progress dialog
}
protected String doInBackground(Void... params) {
//do network operation
return "hello";
}
protected void onPostExecute(String result) {
//dismiss dialog. //set hello to textview
//use the returned value here.
tv.setText(result.toString());
}
}
Consider using robospice (An alternative to AsyncTask. https://github.com/octo-online/robospice.
Make asynchronous calls, Notifies on the ui thread.