Android AlertDialog The specified child already has a parent exception

I have a little problem with AlertDialog in my application. I am showing AlertDialog , so the user can change the text of the button that he just clicked. When I do this for the first time, there is no problem, but if I press the button again, my application will crash with the Exception in the header. Here is the code I'm using:

 public void createDialog(){ new AlertDialog.Builder(Settings.this) .setTitle("Stampii Server Name") .setView(input) .setPositiveButton("Set Name", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String serverName = input.getText().toString(); server.setText(serverName); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } server.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createDialog(); } }); 

Any ideas how I can fix this problem? I have addressed issues like this, but I cannot find a working solution.

Thanks in advance!

+4
source share
2 answers
 .setView(input) 

The variable "input" is not created in the method and is added to a new dialog every time. This means that every time you call your create method, you are trying to add a new parent to the same object. You will need a new "enter" each time you create a dialog, or you can use the same dialog again and again.

+7
source

I had a similar problem. I used showDialog (int id, Bundle args) and implemented

 protected Dialog onCreateDialog(int id,Bundle args) { switch(id) { case ...: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositive... return builder.create(); } } 

My mistake was that before creating a new dialog box I had to use removeDialog (int id), since Android somehow caches the dialog and does not call onCreateDialog () every time showDialog () is called. Therefore, my decision caused

 removeDialog(id); showDialog(id,args); 

and modifying onCreateDialog () by deleting all possible dialogs before the switch statement to avoid conflicts with any other cached dialog.

+1
source

Source: https://habr.com/ru/post/1379117/


All Articles