Karthi
Karthi

Reputation: 13752

alert dialog inside asynctask in android

I need to show the Alertdialog inside Asynctaskin 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.

Upvotes: 6

Views: 7171

Answers (5)

Dale Cooper
Dale Cooper

Reputation: 310

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();
                }
            });

Upvotes: 2

Ihor DIM
Ihor DIM

Reputation: 689

You can call publishProgress() right from doInBackground() and manipulate with UI in onProgressUpdate().

Upvotes: 0

Omar Rehman
Omar Rehman

Reputation: 2044

Show the dialog in onPostExecute() method rather than doInBackground.

Hope that helps

Upvotes: 3

Ben Williams
Ben Williams

Reputation: 6167

I think this might be your problem -- you can't show a dialog from inside doInBackground.

Upvotes: 2

Stephan
Stephan

Reputation: 7388

It isn't possible to manipulate the UI from the background thread. Use handler or the onPre/Post methods of the AsyncTask for that.

Upvotes: 11

Related Questions