35

I am trying to move from one fragment to another.. It shows following error during fragment transaction-

    java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2{41a57218 #3 id=0x1020002}
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)

Below are the classes.I have used following code for fragment transaction

Fragment fragment = new PhotosFragment2();

                        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                        fragmentTransaction.replace(android.R.id.content, fragment);
                        fragmentTransaction.commit();

PhotosFragment.java

   public class PhotosFragment extends Fragment {
        private FragmentActivity myContext;
        @Override
        public void onAttach(Activity activity) {
            myContext = (FragmentActivity) activity;
            super.onAttach(activity);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

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

            rootView.setVerticalScrollBarEnabled(false);
            int[] mThumbIds = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4, R.drawable.album8,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album12, R.drawable.album10,
            };

            int[] mThumbIds2 = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
            };

            CustomGridSingle2 adapter = new CustomGridSingle2(myContext, mThumbIds);
            GridView grid = (GridView)rootView.findViewById(R.id.gridView);
            final ImageView img= (ImageView)rootView.findViewById(R.id.imageView7);
            grid.setFocusable(false);

            grid.setAdapter(adapter);
    grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fragment fragment = new PhotosFragment2();

            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(android.R.id.content, fragment);
            fragmentTransaction.commit();
        }
    });
            CustomGridSingle2 adapter2 = new CustomGridSingle2(myContext, mThumbIds2);
            GridView grid2 = (GridView)rootView.findViewById(R.id.gridView2);
            grid2.setFocusable(false);
            grid2.setAdapter(adapter2);
            grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Fragment fragment = new PhotosFragment2();

                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(android.R.id.content, fragment);
                    fragmentTransaction.commit();
                }
            });

            return rootView;
        }


    }

PhotosFragment2.java

public class PhotosFragment2 extends Fragment {
    private FragmentActivity myContext;
    @Override
    public void onAttach(Activity activity) {
        myContext = (FragmentActivity) activity;
        super.onAttach(activity);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.photos2, container, false);
        myContext.getActionBar().hide();
        return rootView;
    }
}

Activity xml file

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/left_drawer_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bgmenu"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/profilelayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:paddingTop="10dp">


            <ImageView
                android:id="@+id/drawer_profile_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_alignLeft="@+id/drawer_profile_background"
                android:layout_alignRight="@+id/drawer_profile_background"
                android:layout_alignTop="@+id/drawer_profile_background"
                android:layout_marginBottom="7.667dp"
                android:layout_marginLeft="6.5dp"
                android:layout_marginRight="8.3dp"
                android:layout_marginTop="7.667dp"
                android:scaleType="centerCrop"></ImageView>


            <ImageView
                android:id="@+id/drawer_profile_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:scaleType="centerCrop"
                android:src="@drawable/profileblock">

            </ImageView>

            <ImageView
                android:id="@+id/settingicon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_marginLeft="-15dp"
                android:layout_toRightOf="@+id/drawer_profile_background"
                android:background="@drawable/settings" />

            <textview
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/drawer_profile_background"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="5dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceListItemSmall"
                android:textColor="@android:color/white" />


        </RelativeLayout>


        <ListView
            android:id="@+id/list_slidermenu"
            style="@style/buttonStyle"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="30dp"
            android:layout_weight="2"
            android:cacheColorHint="@android:color/transparent"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="1dp"
            android:listSelector="@android:color/transparent"
            android:scrollbars="none" />

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>
Android Developer
  • 7,267
  • 16
  • 62
  • 113
  • fragmentTransaction.replace(R.id.content, fragment); – Alexander Zhak Sep 04 '14 at 12:36
  • @AlexanderZhak shows cannot resolve symbol R.id.content if i change android.R.id.content to R.id.content – Android Developer Sep 04 '14 at 12:38
  • with id `content` should be defined in xml resource which is used in your activity. Please refer to http://developer.android.com/guide/components/fragments.html on how to initialize fragments properly. android.R is an internal system id – Alexander Zhak Sep 04 '14 at 12:41
  • @AlexanderZhak My activity consists of many fragments and i have used fragment transaction in other fragments also which is working fine..only in these two fragments its not working... – Android Developer Sep 04 '14 at 12:45
  • @AlexanderZhak Check whole logcat error updated above – Android Developer Sep 04 '14 at 12:54
  • `No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2` this error says, that there's no View associated with the given ID. ID leads to nowhere. a View in some xml resource must be missing. Try clean project and check your layouts – Alexander Zhak Sep 04 '14 at 12:59
  • You need to acquire the fragment manager like this getActivity().getFragmentManager(); – user608578 Apr 22 '15 at 23:04
  • This happened to me on a phone because the app wasn't checking whether it's in dual-pane mode. The subsequently the `fragmentTransaction.replace()` had nothing to replace ! Of course, on a tablet it is in dual-pane mode. – Someone Somewhere Feb 28 '16 at 13:12

16 Answers16

30

When you use fragmentTransaction.replace(R.id.container,fragment) it will remove any fragments that are already in the container and add your new one to the same container.

Now i can suggest you 2 things.First, if you want to use fragmentTransaction.replace(android.R.id.content, fragment); which you are doing right now,then don't set content for your Activity using setContentView.This should work fine then.To know what exactly android.R.id.content is you can refer this stackoverflow question and answer

Or Secondly, In the layout of your Activity have a FrameLayout whose id is content. And then use

fragmentTransaction.replace(R.id.content, fragment);  
fragmentTransaction.addToBackStack(null);//add the transaction to the back stack so the user can navigate back
// Commit the transaction
fragmentTransaction.commit();  

Hope this helps.

More Info:

From your comments it seems that you are having some problem in getting the idea of using FrameLayout in your Activity's layout(Not of any of the Fragment's layout).From the Documents

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.

So the main purpose of FrameLayout is to block the area required to fit the largest child view. If you use a FrameLayout as Fragment Container you can ensure that you always have the space available to accommodate the largest Fragment's layout.

So you can have your FrameLayout something like this in your Activity's layout xml file

<FrameLayout
    android:id="@+id/content"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
 <!--you can put your existing views of your current xml here, so yes your entire xml is now inside this FrameLayout -->
</FrameLayout>
Community
  • 1
  • 1
Sash_KP
  • 5,403
  • 2
  • 22
  • 34
  • the java classes i posted above are both fragments..do i need to change anything in them or problem is due to the activity that is calling these fragments? – Android Developer Sep 04 '14 at 13:11
  • can u suggest me code which i should add in activity for FrameLayout whose id is content? – Android Developer Sep 04 '14 at 13:12
  • Well for that you need to post your `Activity` here.Need to see what code you have written in your `Activity` right now.You can have a similar `Activity` which you are having now.Just in the layout xml file add a `FrameLayout` and when replacing the `Fragment` use `fragmentTransaction.replace(R.id.content, fragment);`. – Sash_KP Sep 04 '14 at 13:19
  • I don't think there's any problem in your `Fragment`.It's your `Activity` and its Layout xml. If you don't really want any content to be set for your `Activity` then you don't have to write `setContentView` in your `Activity`.You can simple leave that line.And then you can use `fragmentTransaction.replace(android.R.id.content, fragment);` – Sash_KP Sep 04 '14 at 13:29
  • in which layout should i add FrameLayout?Activity layout or PhotosFragment layout?I have not used FrameLayout before..Should I put entire xml file inside FrameLayout? – Android Developer Sep 04 '14 at 15:06
  • I have added more info to my answer.Please see it.You need to add `FrameLayout` to your `Activity`'s layout which is responsible for your `Fragmetn`s.Don't add it in your `Fragment`'s layout itself. – Sash_KP Sep 04 '14 at 15:29
  • If my answer helped you please consider upvoting the answer.And if it solved your problem then accept it as a correct answer.Hopefully this will work for you. – Sash_KP Sep 04 '14 at 16:43
  • above i have posted my activity xml file..i tried using fragmentTransaction.replace(R.id.frame_container, fragment); but it also didn't worked..my activity frame layout id is R.id.frame_container – Android Developer Sep 04 '14 at 16:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60641/discussion-between-sash-kp-and-user3753273). – Sash_KP Sep 04 '14 at 17:05
  • Accepting ur answer for ur effort and as everything u have written is correct..thanks :) – Android Developer Dec 02 '14 at 12:00
23

I don't use getSupportFragmentManager(). I use getChildFragmentManager() and it worked for me. You can try it.

Opal
  • 70,085
  • 21
  • 151
  • 167
NhatVM
  • 1,182
  • 9
  • 19
  • 1
    getChildFragmentManager() is not on support v4 or v13 ... if you are working with v4 or 13 ... How did you mange it? – zizutg Feb 28 '16 at 07:05
16

If you are trying to put Fragment into Fragment, use getChildFragmentManager()

janisz
  • 5,933
  • 4
  • 31
  • 62
Andrei Tr.
  • 199
  • 1
  • 4
  • tnx save my time.But can u explain me when should we take Childfragmentmanager() and Supportfragmentmanager(). – Rojesh Feb 25 '15 at 09:55
  • @Rojesh, as I understand it, you have to use the supportFragmentManager when you putting Fragment into the Activiti(from support lib), but not into other Fragment within Activity – Andrei Tr. Feb 25 '15 at 18:55
8

If you are using ViewPager, use getChildFragmentManager() for pager adapter

viewPager.setAdapter(new ItemsAdapter(getChildFragmentManager()));
georgehardcore
  • 877
  • 13
  • 12
6

You have to set a content view in your Activity that your PhotosFragment is attached.

protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.activity_main);

    //...
}
John Cordeiro
  • 2,021
  • 1
  • 12
  • 12
3

There are 2 most common reasons for this problem

  1. Specifying the wrong layout in setContentView() of the onCreate() method
  2. Error also occurs when having nested Fragments and adding them with getSupportFragmentManager() instead of getChildFragmentManager()

Hope this will help

Summved

Summved Jain
  • 1,126
  • 19
  • 21
1

Since Android 4.2 (API 17) nested fragments become avaliable. See this

To place fragment inside other fragment use getChildFragmentManager()

Also available in support library.

Garg's
  • 2,526
  • 1
  • 31
  • 44
Akber
  • 491
  • 4
  • 10
1

i know this is very late. But it may work for other's.

I declared the id for each layout, like (3rd line bellow)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
Bahu
  • 1,344
  • 2
  • 18
  • 47
1

I had the same error and after trying a lot of things I found that the problem was with the "id" and "getActivity().getSupportFragmentManager()".

Before i implement i like these

txt_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    getChildFragmentManager()
                            .beginTransaction()
                            .replace(R.id.content_frame, new OpportunitiesFragment())
                            .commit();                }

            });

Then i changed to these

 txt_more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
    ## Heading ##
                        getActivity().getSupportFragmentManager()
                                .beginTransaction()
                                .replace(android.R.id.content, new OpportunitiesFragment())
                                .commit();                }
                });
pavithra
  • 87
  • 8
0

Put this block of code in PhotosFragment2 onCreateView method:

View rootView = inflater.inflate(R.layout.photos2, null);

instead of:

View rootView = inflater.inflate(R.layout.photos2, container, false);
John Cordeiro
  • 2,021
  • 1
  • 12
  • 12
0

in my case I had to change

ViewGroup root = (ViewGroup) inflater.inflate(R.layout.sample,
                container);

to

ViewGroup root = (ViewGroup) inflater.inflate(R.layout.sample,
                container, false);
Omid Aminiva
  • 669
  • 5
  • 14
0

This answer highlights a silly mistake that may occur, that arises when nesting fragments or you are converting activities to fragments.

If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.

In BaseFragment.java OnCreateView:

if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, new DifferentFragment())
                    .commit();
        }

return super.onCreateView(inflater, container, savedInstanceState);

Replace super.onCreateView(inflater, container, savedInstanceState); with inflating the correct layout for the fragment:

        return inflater.inflate(R.layout.base_fragment, container, false);
stephen
  • 7,825
  • 14
  • 77
  • 134
0

The problem may be that you add a fragment and beginTransaction in some fragment like

getFragmentManager().beginTransaction().replace(android.R.id.content, ImageBrowseFragment.newInstance(bundle),"ImageBrowseFragment")
            .addToBackStack(null).commit();

I just change getFragmentManager() to getActivity().getSupportFragmentManager()

Then everything goes fine

When you add a fragment in a fragment use android.R.id.content Or Window.ID_ANDROID_CONTENT,I guess it represents the root container of your fragment not the activity. So change to getActivity().getSupportFragmentManager() works it out

Bruce too
  • 21
  • 7
0

If you use ViewPager with fragments (pages) and try to show a new fragment from a page, you will get this error. I think, you cannot reference to a container of an Activity from a ViewPager's page.

In this case you should call getActivity(). Then in Activity write a method that will open a new fragment.

class YourActivity : AppCompatActivity() {

    fun showNewFragment(title: String) {
        val fm = supportFragmentManager
        fm?.beginTransaction()?.apply {
            val fragment = NewFragment.newInstance(title)
            replace(R.id.container, fragment, NewFragment.TAG)
            addToBackStack(null)
        }?.commit()
    }
}

class PageFragment : Fragment() {

    private fun show() {
        (activity as YourActivity).showNewFragment("New fragment")
    }
}    

If you call getParentFragment() and add a new fragment, then you will place a new fragment inside ViewPager:

class ViewPagerFragment : Fragment() {

    fun showNewFragment(title: String) {
        val fm = childFragmentManager
        fm?.beginTransaction()?.apply {
            val fragment = NewFragment.newInstance(title)
            replace(R.id.container, fragment, NewFragment.TAG)
            addToBackStack(null)
        }?.commit()
    }
}

class PageFragment : Fragment() {

    private fun show() {
        (parentFragment as? ViewPagerFragment)?.showNewFragment("New fragment")
    }
}
CoolMind
  • 16,738
  • 10
  • 131
  • 165
0

Make sure the fragment id you are calling is in the class listed in setcontent in onCreate method. For my case, I was editing the layout from linear to constraint. So as not to mess with the working code, I made another layout but messed an id in the process so that what was on oncreate was the edited layout but the fragment being called was from the old layout. Apparently, in the new layout I gave it a different id name. Search the id of your fragment using ctrl+shift+f and see if the search results point to the layout you specified in the oncreate method. Goodluck.

0

The most common mistake that can be happened is, If you have more than one version of XML layout (let say v21 and v23) and you added <fragment> tag in lower version of XML only (or vice-versa). So, please check you added <fragment> tag (or pageGroup, etc) in both of the versions.

Mr Lister
  • 42,557
  • 14
  • 95
  • 136