24

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?

Blaze
  • 2,269
  • 11
  • 40
  • 82

6 Answers6

24

The problem is on this line: alert.setView(input); You added input View that have already parent. Create new input instance.

dieter_h
  • 2,707
  • 1
  • 13
  • 19
18

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);
Xianwei
  • 2,381
  • 2
  • 22
  • 26
3

Put following line

 final AlertDialog alertd = alert.create();

After

 AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
mdDroid
  • 3,135
  • 2
  • 22
  • 34
1

Following situation can also happen (happened to me):

Sometimes when you use a listview you initialize it with an adapter, which belongs to a certain layout. Now lets say the root view of this layout file is a <LinearLayout> with the id "root_view".

If you register now for a context menu in your activity and create an AlerdDialog.Builder which appears after choosing a certain menu element and initialize it with a layout file, which also has a root element with an id called "root_view" where all elements which belong to your AlertDialog are children of it, then those elements "will not be found". You will not be able to access those elements with findViewById, instead you can only access the elements from the <LinearLayout> of your list view and you get the same error message at the line where you call builder.show() (or in the case here alert.show()).

So generally it is a good idea to name the ids of your elements in the layout files uniquely, for your project.

Emad Easa
  • 79
  • 1
  • 10
0

I forgot to call create() on the AlertDialog.Builder. When you call show() without calling the create() method, the AlertDialog instance gets created. This worked the first time but then subsequent clicks got the IllegalStateException. As I was calling show() inside of my onClickListener, it was going to create a new AlertDialog instance every time button was clicked.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
yoyo
  • 137
  • 3
  • 9
0

Add this line at start

View dialog_view= getLayoutInflater().inflate(R.layout.dialog_view, null);
TextInputEditText input = dialog_view.findViewById(R.id.input);

before

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

that way a new instance of input is created and avoid the problem

Angel
  • 190
  • 2
  • 10