Search code examples
androidandroid-dialogillegalstateexceptioncustomdialog

Custom Dialog - You must call removeView() on the child's parent first


I'm using a custom AlertDialog for my project and, when i try to show it the second time it tells me java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

In onCreate of my activity i have:

infoDialog = new QustomDialogBuilder(this);
infoDialog.setTitle("Attenzione");
infoDialog.setTitleColor(Constants.ANTINORI_LIGHT);
infoDialog.setDividerColor(Constants.ANTINORI_LIGHT);
infoDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});

Later i use it as reply of an AsyncTask:

//DO STUFF
infoDialog.setMessage(loginResponse.getMessage());
infoDialog.show();

The first time i show this infoDialog it works fine, but the second time it gives me the IllegalStateException.

I've read a lot of oher post on StackOverflow, but no one seems to solve my problem. Hope someone can help me.


Solution

  • you can use the function below and then call this function when you want to show alert.

    private void showDialog(String message) {
        final Dialog dialog = new Dialog(CustomDialog.this);
        dialog.setContentView(R.layout.custom_alert);
        dialog.setTitle("Custom Dialog");
        TextView text = (TextView) dialog.findViewById(R.id.textDialog);
        text.setText(message);
        ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
        dialog.show();
        Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
        declineButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    

    and call this function like this showDialog(loginResponse.getMessage())