AlertDialog cause WindowManagerBadTokenException when executed second time

I have AlertDialog in one of the activity in my app and it displays and works fine when activity is executed first time. Now if i press back button and again come to same activity (i.e., second time) and try to display alrtdialog, it crashes the app with this error,

08-24 18:09:19.441 I/MonoDroid( 4301): UNHANDLED EXCEPTION:
08-24 18:09:19.471 I/MonoDroid( 4301): Android.Views.WindowManagerBadTokenException: Exception of type 'Android.Views.WindowManagerBadTokenException' was thrown.
08-24 18:09:19.471 I/MonoDroid( 4301): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Users/builder/data/lanes/1978/f98871a9/source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61
08-24 18:09:19.471 I/MonoDroid( 4301): at Android.Runtime.JNIEnv.CallObjectMethod (intptr,intptr) [0x00063] in /Users/builder/data/lanes/1978/f98871a9/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:178
08-24 18:09:19.471 I/MonoDroid( 4301): at Android.App.AlertDialog/Builder.Show () [0x00043] in /Users/builder/data/lanes/1978/f98871a9/source/monodroid/src/Mono.Android/platforms/android-22/src/generated/Android.App.AlertDialog.cs:1626
An unhandled exception occured.

Here is my code,

RunOnUiThread(() =>
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetTitle("Confirmation");
builder.SetMessage("File already exists. Replace it?");
builder.SetCancelable(false);
builder.SetPositiveButton("Replace", delegate
{
SaveFile(fileName, fileString);
});
builder.SetNegativeButton("Cancel", delegate { });
builder.Show();
});

Am i doing anything wrong?

Sign In or Register to comment.