24

I have made an activity A which has a fragment X in it. In fragment X, EditText item has on click event which opens fragment Y. This fragment displays a list of names. I press a name in the list, fragment Y closes and sends the selected name of to fragment X EditText. Here's the code I wrote:

YFragment y = new YFragment();
y.setTargetFragment(x.class, code);
getActivity().getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.frame, y)
    .addToBackStack(null)
    .commit();

In fragment Y I have the code to send the data but the problem is in this block of code above. If I comment out the setTargetFragment line the code will work but no use as data will not be sent. If I run the app this error occurs:

java.lang.IllegalStateException: Fragment y{46d3d31 #3 id=0x7f090069} declared target fragment x{e2c16 #0 id=0x7f090104 android:switcher:2131296516:0} that does not belong to this FragmentManager!

Manaus
  • 407
  • 5
  • 9
Salman Saleem
  • 261
  • 1
  • 3
  • 10
  • your question saved me because h had the same problem and solved When using supportFragmentManager instead of childFragmentManager – Mosa May 24 '20 at 08:14

3 Answers3

34

To use setTargetFragment(), both the new Fragment and the target Fragment must be hosted within the same FragmentManager. The most common case where this would not happen is if you are using Activity.getSupportFragmentManager() or Fragment.getFragmentManager() alongside Fragment.getChildFragmentManager().

Ben P.
  • 52,661
  • 6
  • 95
  • 123
  • 4
    how to make sure that my current fragment and the target fragment have same fragment manager ? – Salman Saleem Nov 01 '17 at 06:35
  • 1
    I checked by debugging and keeping breakpoint.. both of my FragmentManager's id is same still it crashes... So I am wondering... – karan May 16 '18 at 10:06
  • Though might be bad practice, I changed my "getChildFragmentManager()" to "getFragmentManager", while it fixed the issue I could see this creating other issues in circumstances – C. Skjerdal Feb 22 '19 at 15:02
  • @ C. Skjerdal any resolution to use other method? getFragmentManager is deprecated – luke cross May 18 '20 at 19:01
4

In my solution, replace

getChildFragmentManager()

with

Activity.getSupportFragmentManager() or Fragment.getFragmentManager()

that worked for me. Thank Mr.Ben P

phancuongviet
  • 311
  • 2
  • 11
2

To new users where the "getFragmentManager" only work for it but don't want use deprecated method, the method "getParentFragmentManager" work too.

luke cross
  • 321
  • 1
  • 2
  • 19