Search code examples
javaandroidandroid-alertdialog

custom dialog - specified child already has a parent


I've seen other posts but can't make heads nor tails of the following error. Trying to have a dialog pop up on Recycler View item. I do have a similar dialog that works. I must use a different dialog because of different options in the second instance.


public class EditItemDialog extends AppCompatDialogFragment{
    private EditText projectAmountEditText;
    private EditDialogListener listener;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.activity_inventory_item, null);
        

        builder.setView(v)
                .setTitle("Edit Amount")
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int amountChanged = Integer.parseInt(projectAmountEditText.getText().toString());

                        listener.editAmount(amountChanged);
                    }
                });

                projectAmountEditText = v.findViewById(R.id.amount_edit_text_item_activity);
                if(projectAmountEditText == null){
                    //TODO
                }
                builder.show();
            return builder.create();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        try {
            listener = (EditDialogListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() +
                    "must implement EditDialogLister");
        }
    }

    public interface EditDialogListener{
        void editAmount(int amountChanged);
    }
}

Here is the logcat

  Process: com.x.x, PID: 8485
    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        at android.view.ViewGroup.addViewInner(ViewGroup.java:5235)
        at android.view.ViewGroup.addView(ViewGroup.java:5064)
        at android.view.ViewGroup.addView(ViewGroup.java:5036)
    

Solution

  • I had to add a onDestroy override on the dialog to free the View.