alert dialog inside asynctask in android
I need to show the Aler开发者_如何学JAVAtdialog
inside Asynctask
in android , but it won`t show in throws exception.
05-13 14:59:35.522: WARN/System.err(1179): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Thanks.
It isn't possible to manipulate the UI from the background thread. Use handler or the onPre/Post methods of the AsyncTask for that.
Show the dialog in onPostExecute() method rather than doInBackground.
Hope that helps
I think this might be your problem -- you can't show a dialog from inside doInBackground.
There's no problem with reaching UI Thread from backGround thread (more clear: from doInBackground() method): you just have to run runOnUiThread()
method on your context. In my case I'm calling it from doInBackground()
body.
ContactsViewerActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(ContactsViewerActivity.this);
builder.setTitle("Connection problem..")
.setMessage("Could not connect to " + url + ", " +
"try changing your host in the settings to default one :" +
getResources().getString(R.string.default_server_ip) + ":" +
getResources().getString(R.string.default_server_port))
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
You can call publishProgress() right from doInBackground() and manipulate with UI in onProgressUpdate().
精彩评论