After a check demanding the user to switch on internet services and I try to click on a button my app crashes with the error message
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
On this line it crashes, I have tried doing this but not resolved absolutely
if(alert.getContext() != null){
alert.show();
}
This is the complete code
else if (id == R.id.xyz) {
//startActivity(borrowIntent);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("xyz");
input.setFilters(new InputFilter[] {
// Maximum 2 characters.
new InputFilter.LengthFilter(6),
// Digits only.
DigitsKeyListener.getInstance(),
});
// Digits only & use numeric soft-keyboard.
input.setKeyListener(DigitsKeyListener.getInstance());
input.setHint("xyz");
alert.setView(input);
alert.setPositiveButton("Borrow", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(input.getText().length() == 0)
{
input.setError("xyz is required !");
}
else
{
if(isNetworkAvailable())
{
xyz( input.getText().toString());
}else{
//setContentView(R.layout.main);
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setCancelable(false);
builder.setTitle("xyz");
builder.setMessage("Please enable wifi services");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
dialog.dismiss();
}
});
AlertDialog alerts = builder.create();
alerts.show();
}//end of block
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
if(alert.getContext() != null){
alert.show(); //crashes at this line
}
}
Please what am I missing?
The problem is on this line:
alert.setView(input);
You added input
View
that have already parent
.
Create new input
instance.
according to this post, add this check to remove input from it's parent and readd it:
if(input.getParent()!=null)
((ViewGroup)input.getParent()).removeView(input); // <- fix
alert.addView(input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With