6

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.

rupesh
  • 2,865
  • 4
  • 24
  • 50
Karthi
  • 13,624
  • 10
  • 53
  • 76

5 Answers5

11

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

Stephan
  • 7,360
  • 37
  • 46
3

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

Hope that helps

Omar Rehman
  • 2,045
  • 17
  • 17
2

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();
                }
            });
Dale Cooper
  • 310
  • 2
  • 9
2

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

Community
  • 1
  • 1
Ben Williams
  • 6,027
  • 2
  • 30
  • 54
0

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

Ihor DIM
  • 689
  • 1
  • 10
  • 22