无法在尚未调用Looper.prepare()的线程Thread [Thread-5,5,main]中创建处理程序

时间:2019-02-28 06:34:38

标签: java android

以下异常是什么意思;我该如何解决? 这是代码:

    if (response.isSuccessful()) {
                        String message = response.body().string();
                        JSONObject jsonObject = new JSONObject(message);

                        new AlertDialog.Builder(mcontext)
                                .setTitle("title:")
                                .setMessage(TmpPwd)
                                .setPositiveButton("close", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                })
                                .show();
                    }

这是一个例外:

    W/System.err: java.lang.RuntimeException: Can't create handler inside thread Thread[Thread-5,5,main] that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:205)

2 个答案:

答案 0 :(得分:0)

Handler h = new Handler(Looper.getMainLooper());
 h.post(new Runnable() {
  public void run() {
  //here show dialog
}
});

答案 1 :(得分:0)

onResponse内部,在用户界面线程内显示对话框,如下所示:

activity.runOnUiThread(new Runnable() {
  public void run() {
  new AlertDialog.Builder(mcontext)
       .setTitle("title:")
       .setMessage(TmpPwd)
       .setPositiveButton("close", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
        }
    })
    .show();
  }
});