6

In a fragment I setFragmentResultListener and wait for the results:

setFragmentResultListener(EnableFingerPrintFragment.ARG_REQUEST_KEY) { _, bundle ->
    bundle.getString(EnableFingerPrintFragment.ARG_RESULT_KEY)
        ?.let { isActivatedResult: String ->
            // DO something
        }
}
findNavController().navigate(R.id.to_enableFingerPrintFragment,)

When the result comes back this fragment gets Recreated and onCreateView is called.

How to know if the onCreateView is called for the first time fragment created OR it is from result coming back (after result is set in destination fragment)?

How to know if result is set onViewCreated to check this condition?

Morteza Rastgoo
  • 6,772
  • 7
  • 40
  • 61

3 Answers3

0

Probably you should use your viewmodel to retrieve data when your view have been recreated. For example, when you pop up a view from backstack your previous view is recreated but its viewmodel and data inside is not, so think about it.

Hanako
  • 1,637
  • 1
  • 13
  • 16
  • The problem with ViewModel and LiveData is that they persist in the data! This is only an event and if you are thinking about something like SingleLiveEvent, I should remind you to think of the fragment lifecycle when you are communicating between fragments that are finishing and again inflating! – Morteza Rastgoo Jun 16 '21 at 14:48
  • 1
    If ViewModel does not work for you. You should try any other persisting strategy like Shared Preference or Room – Hanako Jun 16 '21 at 18:53
0

You can check if savedInstanceState is null. But in most scenarios you won't need to know if it's first time or second. If set up properly fragment should recreate itself as it was before navigation. Then the only difference in behaviour from creating it for first time is that result listener will be called.

Marcin Mrugas
  • 973
  • 8
  • 17
-1

I Think you must initialize your listener setFragmentResultListener in onCreate and when you came back just your view recreated and onCreate doesn't call twice.

https://developer.android.com/training/basics/fragments/pass-data-between

Also in navigation component new update you can send data between fragments easily by using liveData .

https://stackoverflow.com/a/60757744/7358545

Alireza Nazari
  • 141
  • 1
  • 10
  • There is no Must in position of setting listener! if you come back to any fragment, it gets recreated, regardless of setting listener or not. Maybe I have to follow your second solution, if I don't find a proper solution to this. – Morteza Rastgoo Aug 31 '20 at 10:49
  • 1
    @MortezaRastgoo NavController replace fragments and destroy views and add to back stack, so in fragments onCreate just call once in this situation but onCreateView called for every pop and push in back stack – Alireza Nazari Aug 31 '20 at 11:02
  • This is good. But I need to set a result listener in a very conditional circumstances and not in oncreate or onCreateView – Morteza Rastgoo Aug 31 '20 at 11:31