user4520156
user4520156

Reputation:

How to execute the negative button function when dialog is canceled through back button?

I am having a dialog which must execute some code on canceled. I set a negative button but its not executing when dialog is canceled from back button. here is my code.

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Licence expired");
    builder.setCancelable(false);
    builder.setMessage("Your licence for " + url
            + " has been expired, Please renew it or select another server");
    builder.setPositiveButton("Renew now",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Open url in webview
                    Intent intent = new Intent(MainActivity.this,
                            WebActivity.class);
                    intent.putExtra("ServerDomain", url);
                    startActivity(intent);
                    /*
                     * URL domain; try { domain = new URL(url);
                     * intent.putExtra("ServerDomain", domain.getHost());
                     * startActivity(intent); } catch (MalformedURLException
                     * e) { e.printStackTrace(); }
                     */

                    /*
                     * String url = "http://www.google.com"; Intent i = new
                     * Intent(Intent.ACTION_VIEW);
                     * i.setData(Uri.parse(url)); startActivity(i);
                     */
                }
            });
    builder.setNegativeButton("Switch Server",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showServerList();
                }
            });


        builder.create().show();

Upvotes: 0

Views: 278

Answers (1)

Gopal Singh Sirvi
Gopal Singh Sirvi

Reputation: 4649

Create a cancel listner for dialog.

builder.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO Auto-generated method stub
                showServerList();
            }
        });

Upvotes: 1

Related Questions