I got some problems when trying to show alert dialog in a custom adapter, not inside an activity. In this case, I used AppcompatActivity. After searching and trying many times, I found an answer in the Stackoverflow. Let see it.Normally, the code for showing alert dialog in an activity as shown below.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
 alertDialogBuilder.setMessage("Are you sure, You wanted to make decision");
 alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() { 
@Override public void onClick(DialogInterface arg0, int arg1) { 
Toast.makeText(MainActivity.this,"You clicked yes button",Toast.LENGTH_LONG).show(); } }); 

alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() { Override 
 public void onClick(DialogInterface dialog, int which) { 
  finish(); 
 } 
}); 
AlertDialog alertDialog = alertDialogBuilder.create();
 
alertDialog.show();

Unfortunately, I got some errors.

  1. android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application
  2. You need to use a Theme.AppCompat theme (or descendant) of this activity.

The solution is to customize the styles.xml and change little code. Thanks to this link and this link.

First, customize the styles.xml, I added code below into styles.xml

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert"> 
<!-- Used for the buttons --> 
<item name="colorAccent">#FFC107</item> 
<!-- Used for the title and text --> 
<item name="android:textColorPrimary">#FFFFFF</item> 
< !-- Used for the background --> 
<item name="android:background">#4CAF50</item> 
<item name="android:textColor">@null</item> 
<item name="android:textSize">@null</item> </style>

Second, change the code inside of custom adapter. The point is instead of using “getApplicationContext()”, we used “view.getRootView().getContext();”.

AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.MyAlertDialogStyle); 
builder.setMessage("Delete this data?"); 
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { 
  @Override public void onClick(DialogInterface dialog, int arg1) { 
   } 
}); 

builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
  @Override public void onClick(DialogInterface dialog, int arg1) { 
    dialog.dismiss(); 
  } 
}); 

AlertDialog alert = builder.create(); 
alert.show();
Advertisements