I am try to add a dialog into BluetoothChatService that will prompt to retry the Bluetooth connection if the connection cannot be made or is lost. I am getting a runtime exception when AlertDialog.show() is executed; this error is occurring in Handler.java with the error "Can't create handler inside thread that has not called Looper.prepare()" and mLooper is null. I've tried other solutions found at stackoverflow, such as 'new AlertDialog.Builder(Activity.this)'; nothing has worked.
EDIT: It seems that the approach of a dialog within a thread is the issue. I will re-code the dialog within the constraints of the UI Activity that is creating the thread. Thanks to all that responded.
The code:
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();
}
}