0

I'm working on an Android app with a BottomNavigationBar and a FrameLayout. I have different fragments for every item of the BottomNavBar. I'm trying to send datas from my MainActivity to one of them fragment using Fragment2 fragmentClass = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.fragLayout); (fragLayout is the ID of my FrameLayout.

But when I run my project, I get the following error in the LogCat :

.ClassCastException: com.example.Fragment1 cannot be cast to com.example.Fragment2

What am I doing wrong? The Fragment2 is the active one when this code is running, so why does it say it cannot be cast to Fragment2 ?

Vincent
  • 159
  • 1
  • 2
  • 9
  • ... because it's a `Fragment1`. And I would imagine they do not stand in an (valid) inheritance relationship. – Turing85 Dec 12 '19 at 18:49
  • How and when are you switching to `Fragment2`? – Nitrodon Dec 12 '19 at 18:56
  • I'm switching of fragment when I click an item of the BottomNavBar. When I clicked it, it switches fragment and then run my code to send the datas to the fragment. – Vincent Dec 12 '19 at 18:59
  • So you're still in `onNavigationItemSelected` when you try to send data to `Fragment2`? – Nitrodon Dec 12 '19 at 19:39
  • Basically, onNavigationItemSelected, I call fm.beginTransaction().hide(active).show(Fragment2).commit(); and then I call a function with Fragment2 fragmentClass = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.fragLayout); – Vincent Dec 12 '19 at 19:54
  • 2
    Related: [Android FragmentTransaction commit When?](https://stackoverflow.com/questions/7246479/android-fragmenttransaction-commit-when) – Bö macht Blau Dec 12 '19 at 20:49
  • I've tried with the link you've sent but I'm getting the same error... – Vincent Dec 13 '19 at 17:16

1 Answers1

0

After some hours of searches, I've found the solution to my problem. I just used Fragment2 fragmentTwoClass = (Fragment2) fm.getFragments().get(1); instead of Fragment2 fragmentTwoClass = (Fragment2) fm.getFragmentById(R.id.fragLayout);

Vincent
  • 159
  • 1
  • 2
  • 9