Android Fragment no view found for ID?
Asked Answered
L

40

355

I have a fragment I am trying to add into a view.

FragmentManager fragMgr=getSupportFragmentManager();
feed_parser_activity content = (feed_parser_activity)fragMgr
                                    .findFragmentById(R.id.feedContentContainer);
FragmentTransaction xaction=fragMgr.beginTransaction();

if (content == null || content.isRemoving()) {
    content=new feed_parser_activity(item.getLink().toString());
    xaction
        .add(R.id.feedContentContainer, content)
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        .addToBackStack(null)
        .commit();
    Log.e("Abstract", "DONE");
}

When this code is executed I get the following error in debug..

java.lang.IllegalArgumentException: No view found for id 0x7f080011 
   for fragment feed_parser_activity{41882f50 #2 id=0x7f080011}

feed_parser_activity is a Fragment that is set to Fragment layout in xml.
I am using a FragmentActivity to host the Fragment Layout holding the feed_parser_layout.
Am I coding this correctly above?

Liberati answered 21/9, 2011 at 23:53 Comment(5)
Can you include the XML?Hunk
One can get the same error when making fragment transaction before calling setContentView in ActivityHungry
facing the same issue in Android 5 and Android 6 only when using ViewPager->Fragment->RecyclerView->Fragment with childFragmentManagerPulliam
In my case, I got an id that was not present in my entire app, so must be because some files are not in sync. So I made a sync project with gradle files, then clean project,then rebuild, and run again.Marou
This thread Could be of help https://mcmap.net/q/93943/-java-lang-illegalargumentexception-no-view-found-for-id-0x1020002-android-id-content-for-fragmentMarou
B
459

I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.

The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().

You didn't show us your onCreate() method, so perhaps this is the same problem.

Bartie answered 16/11, 2011 at 21:23 Comment(8)
What do you mean by child of layout specified in setContentView? How to make it child?Cupric
A view is a child of another view if is is declared inside of the parent view in the XML. ie. a TextView inside of a RelativeLayout is a child of the RelativeLayout.Bartie
@howettl: I know it is bit old post. But I am not able fix this issue with your answer. Here is SO question: #25844894 - Can you help me with this please? Thanks!Ruffo
@howettl, can you please help me out with similar issue. #26967123Brittenybrittingham
Happened to me. The downside of CTRL+C CTRL+V.Nelan
You are a life saver. I mistakenly deleted the include code in the main fragment and then I was stuck for 2 hours trying to fix this.Jigsaw
I'm doing doing this in custom Dialog and use a child view of my custom Dialog as container but cannot fix my problemBaylor
Refactoring caused this issue for me.It's not as smart as it seems sometimes.Vatic
P
353

This error also occurs when having nested Fragments and adding them with getSupportFragmentManager() instead of getChildFragmentManager().

Pharmacopsychosis answered 9/8, 2013 at 12:8 Comment(6)
Mine was the other way round. Was trying to add to the main fragment container with calling getChildFragmentManager(). Pointing this out solved it for me. Thanks +1Malita
@Malachiasz: Could you take a look at this question about ViewPager? Thank you #27937750Caiaphas
This was exactly my problem, thank you. Odd though, this only occurred in landscape orientation when calling .show(). Using it to replace the main fragment worked fine.Rainband
That was exactly my problem, thank you very much! It was happening only at some slow devices, so it was hard to understand what was happening exactly.Reames
After coming to this question multiple times I felt like nobody else had my problem, just had to scroll down a bit. It would be nice if they could get the error code to be more specific to say that this could be the case.Grouse
I encountered this error when returning to a fragment from an activity after Android had killed the app in the background. Thanks!Ulcerate
R
82

The solution was to use getChildFragmentManager()

instead of getFragmentManager()

when calling from a fragment. If you are calling the method from an activity, then use getFragmentManager().

That will solve the problem.

Rawlins answered 6/2, 2015 at 7:17 Comment(6)
@surfer190 use getSupportFragmentManager() instead.Tsushima
Changed to getChildFragmentManager() and this works!!Kotick
In my case I was using fragment navigation using viewpager in bottom sheet fragment. Your solution worked brilliantly!! Tons of Thanx bro.Haha
had the same problem and this solved it for me! getChildFragmentManager() instead of getActivity().getFragmentManager() which makes sense once i thought about it :) TY!Bubal
I'm calling the method from an activity but getFragmentManager() is deprecated, now!Elderberry
It works! I'm using it in BottomSheet means I'm adding fragments in bottom sheet.Undercut
G
37

Another scenario I have encountered involves using nested fragments, such as a ViewPager within a Fragment, with its pages also being fragments.

When you do Fragment transaction in the inner fragment(page of ViewPager), you will need

FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

getActivity() is the key here.

Updated on 2023

If you are wondering what exactly happened, you can follow the steps below:

  1. From Android studio menu, select Build | Analyze apk
  2. Select the apk file where you got the error
  3. Then select resources.arsc in File list, and select id from Resouce Types, you will found which id caused this error.
  4. For the example in the image below, It means there is an id named "container" which cannot be found on a Fragment/Activity's layout file.

enter image description here enter image description here

Take the following code for example:

MyFragment myFragment = new MyFragment();
FragmentTransaction fragmentTransaction = requireActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, myFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
  1. On the second line, we got the fragmentManager for activity(where current fragment hosted)
  2. On the 3rd line, replace current fragment with myFragment
  3. Then you need to make sure the layout file of this activity has an view with id=container. otherwise, you will get this error, that's it!
Granivorous answered 17/6, 2015 at 7:27 Comment(1)
yeah... for me all other implementation was fine apart from this. I have directly tried to access the code like this : FragmentTransaction transaction =getSupportFragmentManager().beginTransaction(); Then I got the fragmentmanager using getActivity() separately like you mentioned. It works prettyHackney
C
31

I had this problem (when building my UI in code) and it was caused by my ViewPager (that showed Fragments) not having an ID set, so I simply used pager.setID(id) and then it worked.

This page helped me figure that out.

Considering answered 19/9, 2012 at 15:41 Comment(2)
I had the same problem when used viewPager. The same error was fixed by using viewPager.setCurrentItem(n) before performing transaction. Maybe it will be useful for someone.Hujsak
In my case was in a similar direction, but the problem was that I used a negative value in .setID. Using a positive integer solved the issue.Shrier
U
21

In my case I was trying to show a DialogFragment containing a pager and this exception was thrown when the FragmentPagerAdapter attempted to add the Fragments to the pager. Based on howettl answer I guess that it was due to the Pager parent was not the view set in setContentView() in my FragmentActivity.

The only change I did to solve the problem was to create the FragmentPagerAdapter passing in a FragmentMager obtained by calling getChildFragmentManager(), not the one obtained by calling getFragmentManager() as I normally do.

    public class PagerDialog extends DialogFragment{

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

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

        MyPagerAdapter pagerAdapter = new MyPagerAdapter(getChildFragmentManager());
        ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
        pager.setAdapter(pagerAdapter);

        return rootView;
    }
}
Uncivil answered 11/4, 2013 at 17:12 Comment(3)
getChildFragmentManager() is not accessible from DialogFragmentRummel
Accessible. This one solved my problem. ThanksNiagara
This saved my day. I was trying to use Material Stepper inside a dialog with no avail until I saw this answerPaternity
M
18

This exception can also happen if the layout ID which you are passing to FragmentTransaction.replace(int ID, fragment) exists in other layouts that are being inflated. Make sure the layout ID is unique and it should work.

Mclaurin answered 30/9, 2012 at 9:31 Comment(2)
The compiler does not report if the id is missing in the current layout if its not unique, hence the real problem is not the uniqueness of the id but the omission of the id in the current layout.Ungracious
Yes, check that you replace a fragment in the current container. Use right id of the container (I used another screen's id and got the exception).Greensward
F
18

With Nested fragments

For me by using getChildFragmentManager() instead of getActivity().getSupportFragmentManager() resolved crash

java.lang.IllegalArgumentException: No view found for id

Fiddling answered 4/5, 2018 at 6:46 Comment(1)
but inside adapter cant imprt getchildFragmentManger whyGradient
G
17

An answer I read on another thread similar to this one that worked for me when I had this problem involved the layout xml.

Your logcat says "No view found for id 0x7f080011".

Open up the gen->package->R.java->id and then look for id 0x7f080011.

When I had this problem, this id belonged to a FrameLayout in my activity_main.xml file.

The FrameLayout did not have an ID (there was no statement android:id = "blablabla").

Make sure that all of your components in all of your layouts have IDs, particularly the component cited in the logcat.

Goldia answered 30/5, 2013 at 18:39 Comment(1)
Nice. In Android Studio w/LinuxOS it's here: /home/bob/AndroidStudioWorkspace/HelloWorld/app/build/generated/source/r/release/android/support/v7/appcompat.Crosspollination
C
14

I got this error when I upgraded from com.android.support:support-v4:21.0.0 to com.android.support:support-v4:22.1.1.

I had to change my layout from this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout> 

To this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</FrameLayout> 

So the layout MUST have a child view. I'm assuming they enforced this in the new library.

Cortes answered 28/4, 2015 at 1:36 Comment(0)
M
10

I know this has already been answered for one scenario, but my problem was slightly different and I thought I'd share in case anybody else is in my shoes.

I was making a transaction within onCreate(), but at this point the view tree has not been inflated so you get this same error. Putting the transaction code in onResume() made everything run fine.

So just make sure your transaction code runs after the view tree has been inflated!

Massenet answered 4/9, 2012 at 3:27 Comment(4)
Hmm... in my case it made no difference whether such code was in onCreate or onResumeWimberly
@Wimberly in my case too, solved that with callback from fragment's onAttach. See my answerSlotter
This was my problem exactly. A call to another class to refresh a view state was performing a fragment transaction on a layout that had not yet been inflated. Calling it in onResume() fixed the issue.Bombardon
In onResume(), Make certain any attempts to use FragmentManager occur after super.onResume().Grinnell
T
8

I was facing a Nasty error when using Viewpager within Recycler View. Below error I faced in a special situation. I started a fragment which had a RecyclerView with Viewpager (using FragmentStatePagerAdapter). It worked well until I switched to different fragment on click of a Cell in RecyclerView, and then navigated back using Phone's hardware Back button and App crashed.

And what's funny about this was that I had two Viewpagers in same RecyclerView and both were about 5 cells away(other wasn't visible on screen, it was down). So initially I just applied the Solution to the first Viewpager and left other one as it is (Viewpager using Fragments).

Navigating back worked fine, when first view pager was viewable . Now when i scrolled down to the second one and then changed fragment and came back , it crashed (Same thing happened with the first one). So I had to change both the Viewpagers.

Anyway, read below to find working solution. Crash Error below:

java.lang.IllegalArgumentException: No view found for id 0x7f0c0098 (com.kk:id/pagerDetailAndTips) for fragment ProductDetailsAndTipsFragment{189bcbce #0 id=0x7f0c0098}

Spent hours debugging it. Read this complete Thread post till the bottom applying all the solutions including making sure that I am passing childFragmentManager.

Nothing worked.

Finally instead of using FragmentStatePagerAdapter , I extended PagerAdapter and used it in Viewpager without Using fragments. I believe some where there is a BUG with nested fragments. Anyway, we have options. Read ...

Below link was very helpful :

Viewpager Without Fragments

Link may die so I am posting my implemented Solution here below:

public class ScreenSlidePagerAdapter extends PagerAdapter {
private static final String TAG = "ScreenSlidePager";
ProductDetails productDetails;
ImageView imgProductImage;
ArrayList<Imagelist> imagelists;
Context mContext;

// Constructor
public ScreenSlidePagerAdapter(Context mContext,ProductDetails productDetails) {
    //super(fm);
    this.mContext = mContext;
    this.productDetails = productDetails;
}

// Here is where you inflate your View and instantiate each View and set their values
@Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.product_image_slide_cell,container,false);

    imgProductImage = (ImageView) layout.findViewById(R.id.imgSlidingProductImage);
    String url = null;
    if (imagelists != null) {
        url = imagelists.get(position).getImage();
    }

    // This is UniversalImageLoader Image downloader method to download and set Image onto Imageview
    ImageLoader.getInstance().displayImage(url, imgProductImage, Kk.options);

    // Finally add view to Viewgroup. Same as where we return our fragment in FragmentStatePagerAdapter
    container.addView(layout);
    return layout;
}

// Write as it is. I don't know much about it
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
    /*super.destroyItem(container, position, object);*/
}

// Get the count
@Override
public int getCount() {
    int size = 0;

    if (productDetails != null) {
        imagelists =  productDetails.getImagelist();
        if (imagelists != null) {
            size = imagelists.size();
        }
    }
    Log.d(TAG,"Adapter Size = "+size);
    return size;
}

// Write as it is. I don't know much about it
@Override
public boolean isViewFromObject(View view, Object object) {

    return view == object;
}

}

Hope this was helpful !!

Though answered 14/10, 2015 at 17:58 Comment(2)
Yes, this solution worked, but what if I need difficult construction with own lifecycle and variables, but not only views? It will be used with videoViews and imageViews with play and mute buttons. Nothing helpful for my case?Sophiasophie
I believe this is the reason: https://mcmap.net/q/57920/-viewpager-on-a-view-added-by-windowmanager-getting-quot-java-lang-illegalargumentexception-no-view-found-for-id-quotStrategic
F
8

Just in case someone's made the same stupid mistake I did; check that you're not overwriting the activity content somewhere (i.e. look for additional calls to setContentView)

In my case, due to careless copy and pasting, I used DataBindingUtil.setContentView in my fragment, instead of DataBindingUtil.inflate, which messed up the state of the activity.

Fabria answered 25/7, 2018 at 1:35 Comment(1)
how could we make the same idiotic mistake of copy and paste?? that was exactly my issue. Thank youLakin
K
7

I had the same issue but my issue was happenning on orientation change. None of the other solutions worked. So it turns out that I forgot to remove setRetainInstance(true); from my fragments, when doing a two or one pane layout based on screen size.

Keikokeil answered 5/1, 2014 at 19:40 Comment(1)
turn false your setRetainInstance(true) if you are in a nested fragments, this will fix the error.Diameter
T
5

My mistake was on the FragamentTransaction.

I was doing this t.replace(R.layout.mylayout); instead of t.replace(R.id.mylayout);

The difference is that one is the layout and the other is a reference to the layout(id)

Thant answered 12/11, 2013 at 12:50 Comment(0)
C
5

I use View Binding in my project and was inattentive to add setContentView() after inflating ActivityHelloWorldBinding class:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityHelloWorldBinding.inflate(layoutInflater)

    // Add this line.
    setContentView(binding.root)
}
Conal answered 21/12, 2020 at 9:57 Comment(0)
C
4

This happens when you are calling from a fragment inside another one.

use :

getActivity().getSupportFragmentManager().beginTransaction();
Coffee answered 6/3, 2018 at 6:44 Comment(0)
D
4

I fixed this bug, I use the commitNow() replace commit().

mFragment.getChildFragmentManager()
  .beginTransaction()
  .replace(R.id.main_fragment_container,fragment)
  .commitNowAllowingStateLoss();

The commitNow is a sync method, the commit() method is an async method.

Darkish answered 4/5, 2018 at 7:38 Comment(1)
This finally helped me. Thanks a milLeadwort
H
3

I had this same issue, let me post my code so that you can all see it, and not do the same thing that I did.

@Override
protected void onResume()
{
    super.onResume();

    fragManager = getSupportFragmentManager();

    Fragment answerPad=getDefaultAnswerPad();
    setAnswerPad(answerPad);
    setContentView(R.layout.abstract_test_view);
}
protected void setAnswerPad(AbstractAnswerFragment pad)
{
    fragManager.beginTransaction()
        .add(R.id.AnswerArea, pad, "AnswerArea")
        .commit();
    fragManager.executePendingTransactions();
}

Note that I was setting up fragments before I setContentView. Ooops.

Harwin answered 22/11, 2012 at 2:6 Comment(1)
Thank you! I was doing the same thing, so I put my setContentView inside my onBuildHeadersMussolini
S
3

This page seems to be a good central location for posting suggestions about the Fragment IllegalArgumentException. Here is one more thing you can try. This is what finally worked for me:

I had forgotten that I had a separate layout file for landscape orientation. After I added my FrameLayout container there, too, the fragment worked.


On a separate note, if you have already tried everything else suggested on this page (and the entire Internet, too) and have been pulling out your hair for hours, consider just dumping these annoying fragments and going back to a good old standard layout. (That's actually what I was in the process of doing when I finally discovered my problem.) You can still use the container concept. However, instead of filling it with a fragment, you can use the xml include tag to fill it with the same layout that you would have used in your fragment. You could do something like this in your main layout:

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

    <include layout="@layout/former_fragment_layout" />

</FrameLayout>

where former_fragment_layout is the name of the xml layout file that you were trying to use in your fragment. See Re-using Layouts with include for more info.

Swerve answered 2/1, 2015 at 8:34 Comment(4)
this is a good suggestion, but it doesn't work if one needs to switch fragments dynamically. Also it reduces re-usability, because you can encapsulate behavior (code) in the fragment.Slotter
I definitely agree. Fragments are far better.Swerve
What do you then do with business logic for the included layout? Duplicate? You see Fragments are self contained, both layout files and business logic in their java counterparts .Fredrickafredrickson
@Fredrickafredrickson Sorry, I switched to Flutter a few years ago so I don't remember how to do fragments anymore. Flutter is a lot easier in this regard.Swerve
M
2

In my case I had a SupportMapFragment in a recycler view item (I was using the lower overhead "liteMode" which makes the map appear as non-interactive, almost like a static image). I was using the correct FragmentManager, and everything appeared to work fine... with a small list. Once the list of items exceeded the screen height by a bit then I started getting this issue when scrolling.

Turned out, it was because I was injecting a dynamic SupportMapFragment inside a view, which was inside another fragment, to get around some issues I was having when trying to declare it statically in my XML. Because of this, the fragment placeholder layout could only be replaced with the actual fragment once the view was attached to the window, i.e. visible on screen. So I had put my code for initialising the SupportMapFragment, doing the Fragment replace, and calling getMapAsync() in the onAttachedToWindow event.

What I forgot to do was ensure that my code didn't run twice. I.e. in onAttachedToWindow event, check if my dynamic SupportMapFragment was still null before trying to create a new instance of it and do a Fragment replace. When the item goes off the top of the RecyclerView, it is detached from the window, then reattached when you scroll back to it, so this event is fired multiple times.

Once I added the null check, it happened only once per RecyclerView item and issue went away! TL;DR!

Moline answered 11/1, 2017 at 23:32 Comment(0)
M
2

This issue also happens when you don't put <include layout="@layout/your_fragment_layout"/> in your app_bar_main.xml

Markitamarkka answered 31/3, 2019 at 5:19 Comment(0)
V
2

use childFragmentManager instead of activity!!.supportFragmentManager

Verbatim answered 10/6, 2020 at 12:15 Comment(0)
H
1

I encountered this problem when I tried to replace view with my fragment in onCreateView(). Like this:

public class MyProjectListFrag extends Fragment {


    private MyProjectListFragment myProjectListFragment;

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

        FragmentManager mFragmentManager = getFragmentManager();
        myProjectListFragment = new MyProjectListFragment();
        mFragmentManager
                .beginTransaction()
                .replace(R.id.container_for_my_pro_list,
                        myProjectListFragment, "myProjectListFragment")
                .commit();
    }

It told me

11-25 14:06:04.848: E/AndroidRuntime(26040): java.lang.IllegalArgumentException: No view found for id 0x7f05003f (com.example.myays:id/container_for_my_pro_list) for fragment MyProjectListFragment{41692f40 #2 id=0x7f05003f myProjectListFragment}

Then I fixed this issue with putting replace into onActivityCreated(). Like this:

public class MyProjectListFrag extends Fragment {

    private final static String TAG = "lch";

    private MyProjectListFragment myProjectListFragment;

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

        return inflater
                .inflate(R.layout.frag_my_project_list, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        FragmentManager mFragmentManager = getFragmentManager();
        myProjectListFragment = new MyProjectListFragment();
        mFragmentManager
                .beginTransaction()
                .replace(R.id.container_for_my_pro_list,
                        myProjectListFragment, "myProjectListFragment")
                .commit();

    }
  1. You have to return a view in onCreateView() so that you can replace it later
  2. You can put any operation towards this view in the following function in fragment liftcycle, like onActivityCreated()

Hope this helps!

Hadsall answered 25/11, 2014 at 6:25 Comment(0)
H
1

In my case this exception was thrown when I used different ids for the same layout element (fragment placeholder) while having several of them for different Build Variants. For some reason it works perfectly well when you are replacing fragment for the first time, but if you try to do it again you get this exception. So be sure you are using the same id if you have multiple layouts for different Build Variants.

Hedvig answered 23/4, 2018 at 14:2 Comment(0)
C
1

In our case we have purged/corrupted class.dex file along with gradle compiled outputs. Due to cache recompile weren't tried hence no error, but apk was not having the required file causing this confusing error. A gradle resync and fresh build cleared us from all errors.

// Happy coding

Carrigan answered 19/2, 2020 at 17:55 Comment(1)
I wish this answer was better rated. I had the same issue and I've spent hours to figure it out. The symptom that may help recognizing it is that the log message is pointing to unrelated to the code place resource name. Using Build->Clean Project / Rebuild Project in Android Studio solved the issue.Geber
H
1

As said by https://stackoverflow.com/users/2075875/malachiasz

This solution actually works

getChildFragmentManager().beginTransaction().replace(R.id.cpu_bottomNav_frame,new fragment()).commit();
Hhour answered 22/7, 2021 at 5:48 Comment(0)
P
1

I was having this problem. In my case I have forgotten to add FrameLayout in my Xml File, after adding frame layout, my problem has been solved.

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/wraper"
        android:layout_above="@id/wraper"/>
Probe answered 22/10, 2021 at 4:44 Comment(0)
P
0

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);
Pawl answered 24/2, 2015 at 8:52 Comment(0)
S
0

I've had the same problem when was doing fragment transaction while activity creation.

The core problem is what Nick has already pointed out - view tree has not been inflated yet. But his solution didn't work - the same exception in onResume, onPostCreate etc.

The solution is to add callback to container fragment to signal when it's ready:

public class MyContainerFragment extends Fragment {
    public static interface Callbacks {
        void onMyContainerAttached();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(TAG, "--- onAttach");
        ((Callbacks) activity).onMyContainerAttached();
    }

    //... rest of code
}

And then in activity:

public class MainActivity extends Activity
        implements MyContainerFragment.Callbacks
{
    @Override
    public void onMyContainerAttached() {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.containerFrame, new MyFragment())
                .commit();
    }

    //...
}
Slotter answered 5/3, 2015 at 5:14 Comment(0)
W
0

In my case, i was using a fragment class file to declare a listview adapter class. I just used a different file for the public adapter class and the error was gone.

Willodeanwilloughby answered 14/1, 2016 at 23:38 Comment(0)
C
0

It happens also when you have two views in two fragments with the same ids

Chism answered 27/4, 2019 at 18:11 Comment(1)
This is incorrect. In this case, the code would not even compile.Cascio
P
0

I had the same problem it was caused because I tried to add fragments before adding the container layout to the activity.

Priscilapriscilla answered 14/5, 2019 at 14:4 Comment(0)
M
0

Sometimes it is because you are using a BottomNavigationView. If you open an Intent from the navigation and in that activity you open a fragment lets say

transaction.replace(R.id.container,new YourFragment());

then the Activity won't be able to find the navigation method you are using.

SOLUTION: Change the activity to fragment and handle navigation with addOnBackStack in your app. If you've implemented the Jetpack Navigation just use fragments in your project.

Mita answered 25/10, 2019 at 18:15 Comment(0)
T
0

In my case. I have an Activity with serveral Fragments some time I need to recreate Fragments when

  • language is change
  • fragment layout some need some not need or content change need to recreate
  • other changes
  • I clear all Fragments and set all to null in activity but Fragment already create itself, while it host activty is bean set null, so before call Fragment view check it null

    for example

    Activity{
        fragment
        recreate{
           fragment = null then new instance
        }
    
    }
    
    Fragment{
        if((activity).fragment != null) {
           findViewById()
        }
    
    }
    
    Touching answered 16/1, 2020 at 3:19 Comment(0)
    R
    0

    With navigation library the issue can appear when NavHostFragment haven't an id.

    Wrong declaration:

    <fragment               
         android:name="androidx.navigation.fragment.NavHostFragment"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         app:navGraph="@navigation/myGraph"/>
    

    Right declaration:

    <fragment
         android:id="@+id/myId"               
         android:name="androidx.navigation.fragment.NavHostFragment"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         app:navGraph="@navigation/myGraph"/>
    
    Rigsdaler answered 4/2, 2020 at 10:39 Comment(0)
    O
    0

    A bit late, but might help someone:

    I was overriding onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) (autocomplete suggested this one first and I added setContentView() here)

    Please make sure to override the correct one instead: onCreate(savedInstanceState: Bundle?)

    Obtund answered 23/12, 2020 at 20:25 Comment(0)
    R
    0

    In my case i was using a generic fragment holder using in my activity class and i was replacing this generic fragment with proper fragments at runtime.

    Problem was i was giving id's to both include and generic_fragment_layout , removing id from include solved it.

    Runkle answered 28/12, 2020 at 11:51 Comment(0)
    T
    -1

    I was also getting the same error then, i realised that the issue was with the .add(R.id.CONTAINERNAME) So basically i had giving the id = CONTAINERNAME in wrong xml .. So the solution is to first check that you have given the id = CONTAINERNAME in the xml where you want the fragment to be displayed .. Also note that I was trying to call the fragment form an activity.. I hope so thing small mistake will solve the issue

    REFER ON BASIS OF LATEST VERSION OF ANDROID IN YEAR - 2020

    Throughway answered 5/9, 2020 at 11:40 Comment(1)
    You seem to be implying the same thing as the accepted answerBalance
    M
    -1

    just add viewPager.setOffscreenPageLimit( number of pages );

    Matchlock answered 23/7, 2021 at 12:52 Comment(0)

    © 2022 - 2024 — McMap. All rights reserved.