Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: class
Asked Answered
A

2

10

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?

Aurthur answered 9/7, 2020 at 9:22 Comment(0)
Y
21

Just add @AndroidEntryPoint to your parent Activity class:

enter image description here

And yes, it's a mandatory process if you want to use Hilt. You could use Dagger to get away with this.

Yahairayahata answered 8/8, 2020 at 12:4 Comment(0)
B
0

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
    }
}
Build answered 12/10, 2023 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.