Reputation: 465
I have a alert dialog with a editText area. When I call it a second time, the app crashes with error:
02-28 23:25:08.958: E/AndroidRuntime(11533): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here is my code:
alert = new AlertDialog.Builder(this);
String txt_title = context.getResources().getString(R.string.txt_head_search_coord);
String txt_message = context.getResources().getString(R.string.txt_mess_search_coord);
alert.setTitle(txt_title);
alert.setMessage(txt_message);
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton(context.getResources().getString(R.string.Accept), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
// Do something with value!
dialog.dismiss();
}
});
alert.setNegativeButton(context.getResources().getString(R.string.Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
//UTM Koordinate suchen
btn_search_coord.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
alert.show();
}
});
the alert is defined globally so I can call it in the onClickListener
I'm already dismissing my dialog...
Upvotes: 1
Views: 1204
Reputation: 39397
AlertDialog.Builder.show
create a new instance of Alert
from the content of the Builder
, including the view given in setView
.
Therefore, your input
will be added to both the alerts
. To prevent this, use create
to create a final instance of your AlertDialog
and call show
on this one:
final AlertDialog alertDialog = alert.create();
[...]
// in onClick
alertDialog.show();
On a broader perspective, you should use showDialog(int id)
and the associated methods onCreateDialog
and onPrepareDialog
. However, all this is now deprecated if you use Fragments
, in which case you should use a DialogFragment
Upvotes: 4