Reputation: 29
hi i have AsyncTask in my app but i am unable to change its setMessage
for example :-
private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask1(MainActivity mainActivity) {
context = mainActivity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Checking system...");
this.dialog.setCancelable(false);
this.dialog.setTitle("Please Wait...");
this.dialog.setIcon(R.drawable.ic_launcher);
this.dialog.show();
}
now i want that setmessage to change i tried adding it in doinbackground
protected Boolean doInBackground(final String... args) {
dothis1();
this.dialog.setMessage("one done...");
dothis2();
this.dialog.setMessage("two done...");
but this is making app force close and do not rate it low because i tried my best and searched forum but could able to fix this so asked for hand at this nice community :)
anybody can help ? :)
ERROR
05-13 23:36:34.899: E/AndroidRuntime(2454): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Upvotes: 0
Views: 118
Reputation: 2485
ohmm, you should not update UI from background thread. To update UI, you can do by two ways:
1) Using publishProgress (Progress... values)
and onProgressUpdate(...)
. To do that, you must change your AsynTask
class:
private class ProgressTask1 extends AsyncTask<String, String, Boolean> {
//.......... //your init
@Override
protected Boolean doInBackground(String... params) {
//your background handle
//publish to change UI
String toShow = "your_string_here";
publishProgress(toShow);
//return ...; //your return value
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//detect message and show it.
//this.dialog.setMessage(values[0]);
}
}
2) Using onPostExecute(....)
:
private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
//.......... //your init
@Override
protected Boolean doInBackground(String... params) {
//your background handle
//return ...;//your return value
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
String toShow = "your_string_here";
//this.dialog.setMessage(toShow);
}
}
Upvotes: 1
Reputation: 613
You cannot update the UI from the background.
See AsyncTask.onProgressUpdate to update the UI based on your background progress. :D
Upvotes: 1