當我在backgroud後臺線程AsyncTask中創建AlertDialog時,出現錯誤。如果我在AsyncTask之外創建AlertDialog,它的工作很好。我如何解決這個問題?AsyncTask中的Android java AlertDialog錯誤
final ProgressDialog mDialog = new ProgressDialog(PageAndExercise.this);
mDialog.setMessage(getString(R.string.loading));
mDialog.setCancelable(false);
mDialog.show();
alertDialog2 = new AlertDialog.Builder(this);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
mDialog.dismiss();
alertDialog2.setTitle(getString(R.string.tnxupload));
// Setting Dialog Message
alertDialog2.setMessage(getString(R.string.tnxupload2));
alertDialog2
.setCancelable(false)
.setPositiveButton("", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(getString(R.string.tnxupload3), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialog2.create();
// show it
alertDialog2.show();
}
});
錯誤:
28928-31794/com.example.exampleE/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5
Process: com.example.example, PID: 28928
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
什麼樣的錯誤?你可以添加完整的堆棧跟蹤嗎? – mrek
通過在'execute'方法中傳遞'new Runnable()'你試圖做什麼?並且'execute'不是'static'方法如何使用類名來訪問它? –
由於AsynTask的'doInBackground()'在工作線程上運行,因此您不需要'AsyncTask'內的'Runnable()'。你可以通過asynctask的其他方法訪問應用程序ui。所以在排序AsyncTask是用更有效的方式替代你的'Runnable'和'Message Handler'。 – user370305