AlertDialog.show() makes my app crash

Your variable c should be YourActivity.this instead of getApplicationContext()


There are a couple of things you need to consider.

  1. You are customizing the Alert Dialog such as positioning the button(s) and setting Layout Parameters such as Margins.

    If you are doing this, using the V7 Support's Alert Dialog will resolve the problem. Make sure you have imported the v7 support library in your project.

    Change android.app.AlertDialog.Builder to android.support.v7.app.AlertDialog.Builder

  2. You are creating the Alert Dialog in an Activity or a sub class of the Activity or inside a Fragment Use

    Always pass the Activity context and NOT baseContext or applicationContext

    passing the wrong context (such as the applicationContext or the baseContext) will result in a WindowManager-BadToken exception

In the activity...

AlertDialog.Builder dialog = new AlertDialog.Builder(this);

In the activity's sub class...

AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);

In a Fragment...

AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); // Activity inherits from Context and hence will work.

What I have found is that, heavy customizations to the Alert Dialog works well with the v7 Support AlertDialog class.

In my case, I had to center the Alert Dialog's buttons and set left and right margins, if there was more than a single button. Changing the import to v7 support resolved the issue.

Hope this helps.


i was facing this issue from 1,2 days but i solved this by changing

final Dialog dialogView = new Dialog(getApplicationContext());

to

final Dialog dialogView = new Dialog(Leave_Notification_Activity.this);

you should not use getApplicationContext() instead pass YourActivity.this to solve this issue.