viv
viv

Reputation: 6177

Why does Android NoSuchMethodException occurs at AlertDialog.Builder's setOnDismissListener

I am getting a NoSuchMethodException when using setOnDismissListener on Dialog in Android on a device with 4.1.2.

The same code is working on the emulator with version 4.2.2.

new AlertDialog.Builder(this)
   .setTitle(R.string.select_province)
   .setOnDismissListener(new OnDismissListener() {
        public void onDismiss(DialogInterface arg0) {
       //== other stuff
    }
}).show();

Any ideas?

Upvotes: 12

Views: 2874

Answers (3)

Joey Harwood
Joey Harwood

Reputation: 981

For anyone looking for this answer while using a DialogFragment, Mario's method will result in an IllegalStateException. In this case, Rather than using setOnDismissListener as suggested, one should override the Fragment's existing onDismiss method.

Upvotes: 1

Mario Lenci
Mario Lenci

Reputation: 10542

A workaround to this issue is to just first create the dialog like this:

AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.select_province).create();

and then set the listener directly to the dialog:

dialog.setOnDismissListener( new OnDismissListener() {
    public void onDismiss(DialogInterface arg0) {
   //== other stuff
} );

then if you also want to show it:

dialog.show();

the result is the same and all these methods are supported since API 1.

AlertDialog.setOnDismissListener (DialogInterface.OnDismissListener listener)

AlerDialog.Builder.create()

Upvotes: 27

Voicu
Voicu

Reputation: 17860

The setOnDismissListener method is available only from API 17. Your emulator is running on API 17, your device isn't (it actually runs on API 16). All the API levels are enumerated here.

http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setOnDismissListener(android.content.DialogInterface.OnDismissListener)

Upvotes: 6

Related Questions