Is it mandatory to add @AndroidEntryPoint annotation on all dependent classes like fragment dependent upon activity. Is there any alternative solution for overcome this exception?
Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: class
Asked Answered
Just add @AndroidEntryPoint
to your parent Activity
class:
And yes, it's a mandatory process if you want to use Hilt. You could use Dagger to get away with this.
As a response to your question, there is an alternative solution to overcome this exception.
You can remove @AndroidEntryPoint from your Fragment (or Activity) annotations. Instead, you can obtain dependencies from your Application class, as the application always has the @HiltAndroidApp annotation and has injections. You can inject something there.
Here's a synthetic example:
exampleapplication.kt
@HiltAndroidApp
class ExampleApplication : Application() {
@Inject lateinit var analytics: AnalyticsAdapter
companion object {
private lateinit var instance: ExampleApplication
fun getAnalyticsAdapter(): AnalyticsAdapter {
return instance.analytics
}
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
examplefragment.kt
class ExampleFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_example, container, false)
// Access the AnalyticsAdapter from the ExampleApplication
val analytics = ExampleApplication.getAnalyticsAdapter()
// Now you can use 'analytics' for tracking events or other analytics operations
analytics.trackEvent("Example Event")
return view
}
}
© 2022 - 2024 — McMap. All rights reserved.