AlertDialog.Builder RuntimeException

时间:2012-09-04 13:05:18

标签: android android-alertdialog runtimeexception

我尝试在BluetoothChatService中添加一个对话框,如果无法建立或丢失连接,将提示重试蓝牙连接。我在执行AlertDialog.show()时遇到运行时异常; Handler.java中发生此错误,错误“无法在未调用Looper.prepare()的线程内创建处理程序”,并且mLooper为null。 我尝试过在stackoverflow上找到的其他解决方案,例如'new AlertDialog.Builder(Activity.this)';没有任何效果。

编辑:看起来线程内对话的方法是个问题。我将在创建线程的UI Activity的约束内重新编写对话框。感谢所有回复。

代码:

public class BluetoothChatService {

private Context context;
private final BluetoothAdapter mAdapter;
private int mState;

public BluetoothChatService(Context context) {
    this.context = context;
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    mState = STATE_NONE;
}

private void connectionFailed(String s) {
    // Send a failure message back to the Activity
    stop();
    sendToastMessage(String.format(context.getApplicationContext().getString(R.string.bluetooth_cannot_connect), s));
    createRetryDialog(R.string.bluetooth_cannot_connect, s);
}

// ---------------------------------------------------------------------------------------------
private void createRetryDialog(int msg_id, String err_msg) {
    AlertDialog.Builder alertDialogBuilderRetry;
    alertDialogBuilderRetry = new AlertDialog.Builder(context);
    String message = String.format(context.getApplicationContext().getString(msg_id), err_msg);

    // set title
    alertDialogBuilderRetry.setTitle(context.getApplicationContext().getString(R.string.bluetooth_title_connect_error));

    // set dialog message
    alertDialogBuilderRetry
        .setMessage(message)
        .setCancelable(false)
        .setPositiveButton(context.getApplicationContext().getString(R.string.dialog_button_yes), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // Start the service over to restart listening mode
                initializeBluetooth();
                dialog.dismiss();
            }
        })
        .setNegativeButton(context.getApplicationContext().getString(R.string.dialog_button_no),new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // if this button is clicked, just close
                // the dialog box and do nothing
                mState = STATE_NONE;
                dialog.cancel();
            }
        }).create().show();
}
}

1 个答案:

答案 0 :(得分:0)

确保在调用此函数时,您传递的是活动上下文,而不是应用程序上下文。使用applicationcontext无法显示对话框。

相关问题