Hi guys simple question, when I import the android...
# kodein
m
Hi guys simple question, when I import the android module how can I retrieve, for instance, a
SharedPreferences
?
Copy code
bind<Foo>() with provider {Foo(instance()) }
where my
Foo
class requires in the constracture shared preferences I add the module in this way:
Copy code
kodein.addConfig {
            import(androidModule)
            BaseAppComponent()
        }
a
instance()
should be enough to inject
SharedPreference
into
Foo
. What are you experiencing?
m
it wasn't working cause I have a
ConfigurableKodein
so I had to add the import by :
kodein.addImport(androidModule)
instead.. I just figured out it later, although the import it's done successfully it's not working anyway .. for instance to retrieve
Resources
or
SharedPreferences
I got
Copy code
com.github.salomonbrys.kodein.Kodein$NotFoundException: No provider found for bind<Resources>() with ? { ? }
but in the list of binds I have
Copy code
bind<Resources>() with factory { Context -> Resources }
which should be enough since I retrieve the instance through
kodein.instance()
I don't get it..
a
@mariodroid alright, so
Resources
is bound with a
factory
that requires a
Context
as an argument. So you'd need to provide an instance of
Context
to retrieve the Resources. You have two ways to resolve this problem. Either use
instance(context)
to retrieve
Resources
or use
kodein.addImport(autoAndroidModule(context))
and then
instance()
like you did before
m
umh yeah that makes sense I finally get the difference now I'll try as soon as I get back to work thanks
it all works good
I was expecting in the case I need a
context
instance that kodein with
autoimport
would return me automatically the context from the app. I solved adding it to my component :
bind<Context>() with provider { App.context!! }
is there a better way?
a
@mariodroid you can use
autoAndroidModule(context)
instead of the
androidModule
, that automatically binds the
Context
and a lot of other stuff https://github.com/SalomonBrys/Kodein/blob/734f09ba0e8d80046beec92f29c928b46a4dfd23/kodein-android/src/main/java/com/github/salomonbrys/kodein/android/AndroidModule.kt#L212
m
I did that
it works perfectly
but not in the case I need a instance of
Context
a
@mariodroid inside your kodein module or inside your code?
m
inside my kodein Component
I had to add this
Copy code
fun Kodein.Builder.BaseAppComponent() {

        bind<Context>() with provider { App.context!! }
}
in order to retrieve the context
so now something like this
bind<AuthManager>() with provider { AuthManager(KodeinSharedPreferencesInfo(instance(), SP_AUTH).getSharedPreferences()) }
can actually work