I\'d like to ask for some help: In my app, I have only one activity, a PreferenceActivity
(don\'t need other, it\'s just a simple background-sync app, so the
After introducing crash tracking to a project, I noticed this issue popping up quite frequently and found the same fix worked throughout the project to eliminate the crash:
Example:
MyActivity extends Activity {
ProgressDialog mProgressDialog;
AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
mProgressDialog = new ProgressDialog(MyActivity.this);
mAlertDialog = new AlertDialog.Builder(MyActivity.this).show();
}
@Override
public void onDestroy() {
super.onDestroy();
if(mProgressDialog != null) {
mProgressDialog.dismiss();
}
if(mAlertDialog != null) {
mAlertDialog.dismiss();
}
}
It is misleading that the error message says "unable to add window" as I've found the error happens when you are leaving an Activity and the context that was passed to your Dialog is dead.
The top solution only prevents the crash. For me the problem was that I had referred a wrong context
to show the alert dialog. After passing the correct context
, the problem was solved.
This is usually caused by your app trying to display a dialog using a previously-finished Activity
as a context
. Then check that the activity is not closed by some other apps or other triggers before showing the dialog
if (!isFinishing()) {
//showdialog here
}
Maybe you didn't close or unregister something in your activity. In that case, try unregistering the broadcastreceiver on onDestroy.
I had a very similar issue (which landed me here) and found a very simple fix for it. While my code is different, it should be easy to adapt. Here is my fix:
public void showBox() {
mActive = true;
if (! ((Activity) mContext).isFinishing()) {
mDialogBox.show();
}
}
So, in the sample code in the question, the fix would have been (at a guess):
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (key.equals("checkTest")) {
if (! this.isFinishing()) {
showDialog(1);
}
}
if (key.equals("cancel")) {
dismissDialog(1);
}
}// onSPC
For me this solved the problem.. checking if the dialog is null or not showing and if yes then create again.
// create alert dialog
if (enableNetworkDialog == null || !enableNetworkDialog.isShowing())
enableNetworkDialog = alertDialogBuilder.create();
if (context instanceof AppCompatActivity && !((AppCompatActivity) context).isFinishing())
enableNetworkDialog.show();