FutureShocked FutureShocked - 1 month ago 12
Android Question

onClick methods in an AlertDialog.Builder don't seem to be triggering

I have the following alert dialog being built:

public class myActivity extends Activity {
super.onCreate(savedInstanceState);

... /*Code to initialize intent*/

AlertDialog.Builder builder = new AlertDialog.Builder(myActivity.this);
builder.setMessage(R.string.launch_preference);
builder.setPositiveButton(R.string.term_preference, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
intent.putExtra("launchType", "launchTerm");
dialog.cancel();
try { startActivity(intent); }
catch (ActivityNotFoundException e) { showUpdateError(); }
finish();
}
});
builder.setNegativeButton(R.string.xterm_preference, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
intent.putExtra("launchType", "launchXTerm");
dialog.cancel();
try { startActivity(intent); }
catch (ActivityNotFoundException e) { showUpdateError(); }
finish();
}
});
builder.create().show();
}

private void showUpdateError() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("myApp is attempting to launch myOtherApp. It is either missing or out of date Please update it and try again.");
builder.setPositiveButton("Got it!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}


Running this activity causes the alert dialog to appear, but clicking either of its button just causes the app to close.

I'm migrating a family of apps to a new ecosystem using a new type of intent to communicate between them. The idea is that if myOtherApp hasn't been updated, the second alert dialog will appear after the first disappears. Unfortunately, the onClick methods aren't even entered during debug mode.

Answer

You need to cancel the dialog after you start the activity. Remove finish(), which simply kills your activity.

Comments