Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yes/NO Alert Dialog box in Android

Tags:

android

I want to Show an Alert Dialog Box in android on onBackPressed() event

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

    //@Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
        case DialogInterface.BUTTON_POSITIVE:
            //Yes button clicked
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            //No button clicked
            break;
        }
    }
};

But I am getting error when executing it in onBackPressed() event

@Override
public void onBackPressed() {
    super.onBackPressed();  
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
        .setNegativeButton("No", dialogClickListener).show();

}

Error : "com.java.mypkg has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@406c3798 that was originally added here"

Do I have missed something. Pls help.

like image 464
senps Avatar asked Dec 04 '22 15:12

senps


2 Answers

Yes, don't invoke that as per previous user's response. super.onBackPressed(); will onStop method of the Activity. Instead of onBackPressed(); you can use onKeyDown for your requirement. If you need to open an AlertDialog when you press the back button you can simply try that with KeyEvent

For example -

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub

    switch(keyCode)
    {
    case KeyEvent.KEYCODE_BACK:
        AlertDialog.Builder ab = new AlertDialog.Builder(AlertDialogExampleActivity.this);
        ab.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
        .setNegativeButton("No", dialogClickListener).show();
        break;
    }

    return super.onKeyDown(keyCode, event);
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
        case DialogInterface.BUTTON_POSITIVE:
            //Yes button clicked
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            //No button clicked
            break;
        }
    }
};

When you're overriding onKeyDown method it will detect back key with your KEYCODE_BACK

Hope this helps you.

like image 162
Praveenkumar Avatar answered Dec 20 '22 16:12

Praveenkumar


Dont invoke super.onBackPressed(); cause it will call onStop method of the activity.

And Displaying a dialog over an activity which has been finished, will leak window.

like image 41
jeet Avatar answered Dec 20 '22 16:12

jeet