Returning data to CrimeFragment

I follow the chapter without complaint or confusion until page 238 when we begin to return data to crimefragment.
Why do we need to setTargetFragment then send the result through intent.putExtra?

Why cant we set the args for crimefragment how it was done in listing 12.5 for datepickerfragment?

Wondering the same. Can someone help clarify?

Edit: fragment arguments only seem useful for passing data “forward” - when you’re making a new fragment. As mentioned previously in the book, the arguments have to be assigned after creation but before being attached. In this case, there already IS a fragment we want to give data to AND it’s already attached (view? fragment manager? container id? not sure…). So the arguments won’t be possible. Instead, there has to be some way for the child fragment to “be observed” by its calling fragment. In this case, the author decides to use setTargetFragment to give the child an idea of who called it, an onClickListener to assign data and call back onActivityResult on the parent.

Can someone tell me if I’m on the right track here?

Yes, the issue here is that we are passing back data to a fragment that already exists. Fragment arguments are used when you create a new fragment.

The real trick here is that we need a solution that works across the death and recreation of both of our fragments (CrimeFragment and the dialog fragment). The way we solve this problem in the book is with the target fragment API. Once we set CrimeFragment as the target fragment on the dialog, it will be re-connected for us across the death and recreation of these fragments (through rotation or low-memory death). Then, we can just call methods on the target fragment.

You can define your own methods if you want:

((CrimeFragment) getTargetFragment()).setDate(...)

We chose to use the onActivityResult method because every Fragment has this method and our dialog won’t need to know any specific details about the fragment it returns data to. Any fragment can use the date dialog.

Any idea on why we use the following validation when we have already set CrimeFragment as the target fragment and we expect it to always launch the DatePickerFragment and the date picker reporting back on the new date that is set by the user.

   private void sendResult(int resultCode, Date date) {
       if (getTargetFragment() == null) return;

       Intent data = new Intent();
       data.putExtra(EXTRA_DATE, date);

       getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, data);

Is it to make the DatePickerFragment modular? Or is it to avoid the lint warning that the .onActivityResult may throw a NullPointerException?

Yea, our goal here was to make the DatePickerFragment a reusable component that doesn’t know which Fragment it’s sending data back to.

1 Like