在线程执行期间创建警报框时出错

时间:2013-10-24 19:03:35

标签: android

我正在尝试在线程中创建alertbox但是在这里得到错误是我的线程和警报框的代码,这个警报框成功地运行了thread.posting代码和错误日志,帮助我。

Thread paypalThread = new Thread() {
        @Override
        public void run() {
            try {
                PackageManager pm = getApplicationContext().getPackageManager();
                ApplicationInfo appInfo = pm.getApplicationInfo(
                        "com.mothistorycheck", 0);
                String appFile = appInfo.sourceDir;
                long installed = new File(appFile).lastModified();
                Date date = new Date(installed * 1000L);
                Date currentDate = Calendar.getInstance().getTime();
                Calendar cal=Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.YEAR, 1);
                Date installedPlusYear = cal.getTime();
                System.out.println(installedPlusYear);      


                if (currentDate.compareTo(date)==-1) {
                    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                    .setNegativeButton("Close",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            }).create();
            // Setting Dialog Title
            alertDialog.setTitle("Alert");

            // Setting Dialog Message
            alertDialog
                    .setMessage("Either MOT test number or Document Reference Number should be entered!");

            alertDialog.setCancelable(true);

            // Setting Icon to Dialog
            // alertDialog.setIcon(R.drawable.tick);

            // Showing Alert Message
            alertDialog.show();
            return;

                }else
                    System.out.println("000000");
                 // int comparison2 = oneYearFromNow.compareTo(date);

                // sleep(31536000);
            }

            catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
            //  finish();
                Intent i = new Intent(getApplicationContext(),
                        SplashActivity.class);
                //startActivity(i);
            }
        }
    };
    paypalThread.start();

此处记录详细信息

    10-24 12:32:23.462: E/AndroidRuntime(20705): FATAL EXCEPTION: Thread-5842
10-24 12:32:23.462: E/AndroidRuntime(20705): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
10-24 12:32:23.462: E/AndroidRuntime(20705):    at android.os.Handler.<init>(Handler.java:121)
10-24 12:32:23.462: E/AndroidRuntime(20705):    at android.app.Dialog.<init>(Dialog.java:107)
10-24 12:32:23.462: E/AndroidRuntime(20705):    at android.app.AlertDialog.<init>(AlertDialog.java:114)
10-24 12:32:23.462: E/AndroidRuntime(20705):    at android.app.AlertDialog$Builder.create(AlertDialog.java:913)
10-24 12:32:23.462: E/AndroidRuntime(20705):    at com.mothistorycheck.MainActivity$1.run(MainActivity.java:132)

3 个答案:

答案 0 :(得分:0)

这是因为您可以在不是UI主线程的线程内操作视图,您可以使用Handler来执行对话框,还可以看到Handler ExampleHandling View inside Handler

答案 1 :(得分:0)

您必须在UI线程内创建AlertDialog否则它永远不会工作。如果您使用不同的线程MessageHandler,或者可以使用runOnUiThread(使用runnable)在内部创建对话框。

在onCreate()或onResume()

中创建一个处理程序
..onCreate(){
...mHandler=new Handler();
}

然后在Thread()内使用:

mHandler.post(new Runnable{
    public void run(){
        //Be sure to pass your Activity class, not the Thread
        AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
        //... setup dialog and show
    }
});

答案 2 :(得分:0)

如前所述,您无法在UI线程之外对UI进行任何更改。我建议你使用AsyncTask&amp;在onPostExecute回调中创建对话框。这就是你如何使用它:

public void verifyPaypal() {
    PayPalVerifyTask task = new PayPalVerifyTask();
    task.execute((Void) null);
}

public class PayPalVerifyTask extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            PackageManager pm = getApplicationContext().getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(
                    "com.mothistorycheck", 0);
            String appFile = appInfo.sourceDir;
            long installed = new File(appFile).lastModified();
            Date date = new Date(installed * 1000L);
            Date currentDate = Calendar.getInstance().getTime();
            Calendar cal=Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.YEAR, 1);
            Date installedPlusYear = cal.getTime();
            System.out.println(installedPlusYear);      

            if (currentDate.compareTo(date)==-1) {  
                return true; // this will be passed to onPostExecute
            }else
                System.out.println("000000");
                // int comparison2 = oneYearFromNow.compareTo(date);
                // sleep(31536000);
                return false;
            }
        catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
        //  finish();
            Intent i = new Intent(getApplicationContext(),
                    SplashActivity.class);
            //startActivity(i);
        }
    }

    @Override
    protected void onPostExecute(final Boolean show_alert) {
        if (show_alert) {
            AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
            .setNegativeButton("Close",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int id) {
                            dialog.cancel();
                        }
                    }).create();
            // Setting Dialog Title
            alertDialog.setTitle("Alert");

            // Setting Dialog Message
            alertDialog
                    .setMessage("Either MOT test number or Document Reference Number should be entered!");

            alertDialog.setCancelable(true);

            // Setting Icon to Dialog
            // alertDialog.setIcon(R.drawable.tick);

            // Showing Alert Message
            alertDialog.show();
        }
    }
}

运行verifyPaypal()以启动任务。