6

I got following crash in crashlytics, but cannot reproduce issue. There is no exception explanation which I can use to trace:

dagger.hilt.internal.Preconditions.checkState (Preconditions.java:83)
com.xxx.xxx.ui.base.Hilt_BaseFragment.onAttach (Hilt_BaseFragment.java:46)
androidx.fragment.app.Fragment.onAttach (Fragment.java:1783)
com.xxx.xxx.ui.base.Hilt_BaseFragment.onAttach (Hilt_BaseFragment.java:36)
androidx.fragment.app.Fragment.performAttach (Fragment.java:2922)
androidx.fragment.app.FragmentStateManager.attach (FragmentStateManager.java:464)

In BaseFragment, there are some injected objects.

@AndroidEntryPoint
abstract class BaseFragment : FragmentForLifeCycles() {

    @Inject
    lateinit var injectedClass: InjectedClass

}

There is no retained fragment (I mean there is no setRetainInstance(true) for the fragments)

In some of the fragments which are derived from BaseFragment are annotated with @AndroidEntryPoint or not according to the needing of injection on that fragment.

Here is the generated hilt class (Hilt_BaseFragment.java) onAttach block where the error is occurred;

@Override
  @CallSuper
  @MainThread
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    Preconditions.checkState(componentContext == null || FragmentComponentManager.findActivity(componentContext) == activity, "onAttach called multiple times with different Context! Hilt Fragments should not be retained.");
    initializeComponentContext();
    inject();
  }
Hakan Erbaş
  • 139
  • 1
  • 10

2 Answers2

0

I had similar issue. So I'm answering in case anyone need solution.

You did not post fragment consumer activity code or full fragment code. I will show my solution code part.

In my case I had following code:

 ////
companion object {
    const val TAG = "AnotherFragment"

    var instance: AnotherFragment? = null

    fun oneInstance(): AnotherFragment{
        if (instance == null)
            instance = AnotherFragment()
        return instance!!
    }
}

Note: Do not use the instance multiple times. If you consume this instance in onCreate on a parent fragment, and the app goes in background and comes back to the parent fragment, it will get called multiple times and give you the hilt error.

The solution is to create a new instance everytime.

On consumer fragment:

//do it like:
val anotherFrament = AnotherFrament() // ✔️ this solved my issue

// do not do it like this:
 val anotherFrament = AnotherFrament.oneInstance() // ⚠️❌

//if data consistency issue appears or something else, handle with lifecycle events.

I hope to help someone.

Rifat
  • 1,700
  • 3
  • 20
  • 51
0

check if you are using setRetainFragment(true) if so remove it ,because this will keep fragment and hilt need new instance of fragment every time