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

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!

This question is related to android android-layout android-fragments

The answer is


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;
    }
}

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;
}

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


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.


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:

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

Now with the LinearLayout removed:

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

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.


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

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" />

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.


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


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

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference