google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.35k stars 2k forks source link

Unable to add window -- token null is not valid; is your activity running? #4004

Closed jonrysimbolon closed 11 months ago

jonrysimbolon commented 11 months ago

I want to initialize popup dialog with @ApplicationContext but still show

"Unable to add window -- token null is not valid; is your activity running?"

this is mine

Loading.kt

@ActivityScoped
class Loading @Inject constructor(
    @ActivityContext var context: Context
) : CustomDialog {

    private val dialog = Dialog(context)
    private val constraintLayout = ConstraintLayout(context)
    private val inflater = LayoutInflater.from(context)

    init {
        init()
    }

    override fun init() {
        val dialogView = inflater.inflate(R.layout.dialog_loading, constraintLayout)
        dialog.setContentView(dialogView)
        dialog.window?.apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setDimAmount(1f)
            setFlags(
                WindowManager.LayoutParams.FLAG_DIM_BEHIND,
                WindowManager.LayoutParams.FLAG_DIM_BEHIND
            )
        }
        dialog.setCancelable(false)
    }

    override fun show(show: Boolean) {
        dialog.let {
            if (show) {
                it.show()
            } else {
                it.dismiss()
            }
        }
    }
}

Module.kt

@Module
@InstallIn(ActivityComponent::class)
object DialogModule{

    @ActivityScoped
    @Provides
    fun provideLoadingDialog(
        @ApplicationContext context: Context
    ): CustomDialog = Loading(context)

and snippet of

HomeFragment.kt

@Inject
lateinit var loadingDialog: CustomDialog

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    loadingDialog.show(true)
}

How do i fix it ?

bcorso commented 11 months ago

Sorry, that is not a Dagger error, so we won't be able to help here. You can try asking your question on StackOverflow.

jonrysimbolon commented 11 months ago

i'm sorry before sir, but if not use hilt, my code is work (i use lazy), i just want to show the dialog popup with hilt, if my question makes you confused, i'm sorry in advance 🙏

kuanyingchou commented 11 months ago

FWIW, use @ActivityContext instead of @ApplicationContext in your provideLoadingDialog() should make it work.

jonrysimbolon commented 11 months ago

@kuanyingchou thanks, you saved my day