java.lang.IllegalStateException: The specified child already has a parent

Go To StackoverFlow.com

89

I am using fragments, when I instantiate a fragment the first time it it. but the second time I got this exception. I couldn't find the line where I got the error?

 04-04 08:51:54.320: E/AndroidRuntime(29713): FATAL EXCEPTION: main
    04-04 08:51:54.320: E/AndroidRuntime(29713): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.view.ViewGroup.addViewInner(ViewGroup.java:3013)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.view.ViewGroup.addView(ViewGroup.java:2902)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.view.ViewGroup.addView(ViewGroup.java:2859)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.view.ViewGroup.addView(ViewGroup.java:2839)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.support.v4.app.NoSaveStateFrameLayout.wrap(Unknown Source)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.support.v4.app.BackStackRecord.run(Unknown Source)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(Unknown Source)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.support.v4.app.FragmentManagerImpl$1.run(Unknown Source)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.os.Handler.handleCallback(Handler.java:587)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.os.Handler.dispatchMessage(Handler.java:92)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.os.Looper.loop(Looper.java:132)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at android.app.ActivityThread.main(ActivityThread.java:4126)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at java.lang.reflect.Method.invokeNative(Native Method)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at java.lang.reflect.Method.invoke(Method.java:491)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
    04-04 08:51:54.320: E/AndroidRuntime(29713):    at dalvik.system.NativeStart.main(Native Method)

Here are what i do when i click on an element of my list fragment.

// If we are not currently showing a fragment for the new
 // position, we need to create and install a new one.
 RouteSearchFragment df = RouteSearchFragment.newInstance(index);

 // Execute a transaction, replacing any existing fragment
 // with this one inside the frame.
 FragmentTransaction ft = fragmentManager.beginTransaction();
 ft.replace(R.id.details_full, df);
 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
 ft.commit();

The first time it is Ok, I click element2 from list, it's also ok; but when I return to element1 I got this bug.

Thanks every one!

2012-04-04 08:00
by haythem souissi
need to call layoutView.removeAllViews(); before add views to layou - ρяσѕρєя K 2012-04-04 08:05
@imrankhan wrong! You can add without removing all. The most important part is missing and as there is no custom package in the stacktrace, I suggest you remove some code and test it step by step.. - WarrenFaith 2012-04-04 08:20
i add more details, please can you see that - haythem souissi 2012-04-04 09:18
What's this RouteSearchFragment class?? Can't find any reference in Android docs. Please update the class definition too - noob 2012-04-04 09:48


28

When you override OnCreateView in your RouteSearchFragment class, do you have the

if(view != null) {
    return view; 
}

code segment?

If so, removing the return statement should solve your problem.

You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
        }
    }
2012-04-04 12:09
by Medo
@Override public void onDestroyView() {

super.onDestroyView();

ViewGroup parentViewGroup = (ViewGroup) mRoutesSearchViewContainer.getParent();

if( null != parentViewGroup ) {

parentViewGroup.removeView( mRoutesSearchViewContainer ); }

- haythem souissi 2012-04-04 14:37

@Medo: Can you give brief explaination for this. I have the same error shown in the logcat. as you have given the suggestion "remove the return statement should solve your problem" but we need to return View object in onCreateView() method. can you provide snippet code for you're explanation. Thank you - Krishna Prasad 2013-02-07 11:49
@Krishna Just inflate and return the view as you would normally. You can skip the whole if statement - Medo 2013-02-08 15:10
For me, I just had to replace return inflater.inflate(R.layout.fragment_search, container); with return inflater.inflate(R.layout.fragment_search, container, false);Sufian 2014-07-13 14:00


364

Sorry to post to an old question but I was able to fix it using a totally different solution. I was getting this exception but I changed the first line of my onCreatView override from this:

View result = inflater.inflate(R.layout.customer_layout, container);

...to this:

View result = inflater.inflate(R.layout.customer_layout, container, false);

I have no idea why but using the override that accepts the boolean as the third param fixed it. I think it tells the Fragment and/or Activity not to use the "container" as the parent of the newly-created View. HTH!

2012-10-19 00:47
by Patrick
Don't be sorry - this was very useful to me, and clearly a number of other people. Thanks - head in the codes 2013-06-05 23:28
Had same problem. It worked for me fine. Thanks - rootpanthera 2013-06-17 13:17
Thanks a lot, I keep forgetting this and coming back to this answe - noloman 2016-07-13 14:06
@Patrick, The first attaches the inflated view to the container, adding the false flag specifies you not want to add the inflated view to the container - Ne0 2017-06-15 14:12
and I keep coming back to this post and finding out that this is THE ANSWER : - noloman 2018-02-06 12:16


43

I have facing this issue many time. Please add following code for resolve this issue :

@Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup parentViewGroup = (ViewGroup) view.getParent();
            if (parentViewGroup != null) {
                parentViewGroup.removeAllViews();
            }
        }
    }

Thanks

2013-04-15 11:54
by Hardik
Thank you on this solution :) I have a very specific case where I can not use inflater to solve this.

You saved me lots of tim - Bojan 2013-06-06 13:12

I'm sorry, I don't quite understand cuz I'm new to android - Zin Win Htet 2014-09-05 08:03
In view.getParent(); Where dose view object come from - Zin Win Htet 2014-09-05 08:04
Cristy YG: Take a View instance as a global variable, and inflate your layout xml on above global variable. are you following me or not - Hardik 2014-12-01 06:57
Yes, view instance declare as global - Hardik 2015-05-22 06:15


34

If you have this statement..

View view = inflater.inflate(R.layout.fragment1, container);//may be Incorrect 

Then try this.. Add false as third argument.. May be it could help..

View view = inflater.inflate(R.layout.fragment1, container, false);//correct one
2014-07-18 07:52
by Dhananjay M
This should be marked as the correct answer - Joseph 2018-07-01 17:44


21

I had this code in a fragment and it was crashing if I try to come back to this fragment

if (mRootView == null) {
    mRootView = inflater.inflate(R.layout.fragment_main, container, false);
} 

after gathering the answers on this thread, I realised that mRootView's parent still have mRootView as child. So, this was my fix.

if (mRootView == null) {
    mRootView = inflater.inflate(R.layout.fragment_main, container, false);
} else {
    ((ViewGroup) mRootView.getParent()).removeView(mRootView);
}

hope this helps

2013-09-04 11:29
by user1736525
+1 helped me. Especially true if your activity stays but fragment manager is adding new fragments on top. when it gets back to the first fragment, need to make sure the old root view gets removed. Thanks - Bundeeteddee 2013-11-20 08:18
It helped me a lot. I've been finding that solution for 3 days. Simple and pretty answer - Zin Win Htet 2014-09-05 08:31
Wow! finally it worked for me! grat solution. thanks - avisper 2017-07-05 08:23
I dont have a rationale why "(ViewGroup) mRootView.getParent()).removeView(mRootView);" works in contrast to directly calling " .removeView(mRootView)" But this works for me as well, I'm testing on Android 8.0 and 9.0. Thanks bud - Khay 2019-02-16 01:33


15

It also happens when the view returned by onCreateView() isn't the view that was inflated.

Example:

View rootView = inflater.inflate(R.layout.my_fragment, container, false);

TextView textView = (TextView) rootView.findViewById(R.id.text_view);
textView.setText("Some text.");

return textView;

Fix:

return rootView;

Instead of:

return textView; // or whatever you returned
2014-12-19 20:37
by Mateus Pires
This is a silly mistake. Happened once to me : - Pavan 2015-02-25 07:16
Thanks! it helped me - Sudheesh Mohan 2015-07-03 10:27


5

I had this problem and couldn't solve it in Java code. The problem was with my xml.

I was trying to add a textView to a container, but had wrapped the textView inside a LinearLayout.

This was the original xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:textColor="#fff"
        android:background="?android:attr/activatedBackgroundIndicator"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

</LinearLayout>

Now with the LinearLayout removed:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:textColor="#fff"
        android:background="?android:attr/activatedBackgroundIndicator"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

This didn't seem like much to me but it did the trick, and I didn't change my Java code at all. It was all in the xml.

2015-10-13 14:00
by DroidCrafter


2

You are adding a View into a layout, but the View already is in another layout. A View can't be in more than one place.

2012-04-04 08:21
by noob
i added more details to my question, please can you see that - haythem souissi 2012-04-04 09:19


1

This solution can help :

public class FragmentItem extends Android.Support.V4.App.Fragment
{
    View rootView;
    TextView textView;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView != null) 
        {
            ViewGroup parent = (ViewGroup)rootView.Parent;
            parent.RemoveView(rootView);
        } else {
            rootView = inflater.Inflate(Resource.Layout.FragmentItem, container, false);
            textView = rootView.FindViewById<TextView>(Resource.Id.textViewDisplay);            
        }
        return rootView;
    }
}
2014-06-18 06:32
by Bhavit S. Sengar
I think rootView will always be null since you didn't initialize it - Zin Win Htet 2014-09-05 08:11
rootView always be nul - Thinsky 2015-10-19 03:34


0

in your xml file you should set layout_width and layout_height from wrap_content to match_parent. it's fixed for me.

<FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
2018-07-15 07:38
by Evan Ngo


0

I solved it by setting attachToRoot of inflater.inflate() to false.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_overview, container, false);
    return view;
}
2018-09-26 10:45
by Mr. B.
Ads