首页 文章

无法在未调用Looper.prepare()的线程内创建处理程序 - Alertdialogbox [duplicate]

提问于
浏览
0

可能重复:无法在未调用Looper.prepare()的线程内创建处理程序

我想在线程中调用alertdialogbox,如下所示

public class connect implements Runnable
     {
     public void run()  //run method

    {

        AlertDialog.Builder alert = new AlertDialog.Builder(cordovaExample.activity);

        alert.setTitle("Confirm");
        alert.setMessage("Are you sure?");

        alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // Do nothing but close the dialog

                dialog.dismiss();
            }

        });

        alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();
            }
        });

        AlertDialog s = alert.create();
        alert.show();
       }
     }

我从以下活动中调用此线程

public class cordovaExample extends DroidGap
{
    Context mcontext;

    public static cordovaExample activity;
private static MediaPlayer  music=null;
    @Override
    public void onCreate(Bundle savedInstanceState)

        {
            super.onCreate(savedInstanceState);

            activity=this;

                             super.init();



                   new Thread(new connect(this)).start();

                     }
                }

但它的给出错误无法在未调用Looper.prepare()的线程内创建处理程序

任何帮助将不胜感激

2 回答

  • 2

    在App UI线程中写下这一行

    alert.show();
    

    像这样的东西

    MainActivity.this.runOnUiThread(new Runnable() {
    
            public void run() {
                  alert.show();
    
            }
        });
    
  • 1

    你不能在线程运行时对ui进行更改 . 如果你想这样做,使用Handler或runOnUiThead或者最好的选择就是使用AsyncTask .

相关问题