i get this error while using shared preference in ...
# multiplatform
p
i get this error while using shared preference in android. 'java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference'
j
Seems you have a null
Context
reference. How is this related to multiplatform? Seems you're using a Java API that allows a platform type instead of nullable API. Most of Android's APIs have been annotated
@Nullable
or
@NonNull
for a while for better interop with Kotlin's nullable types. Where are you getting your
Context
reference from?
p
Copy code
actual typealias KMMContext = Application
here
j
Where are you getting your
applicationContext
reference you're passing here?
Copy code
val pref = KMMPreference(applicationContext)
p
Copy code
actual typealias KMMContext = Application
here, this is from
j
That's just defining a platform typealias. You actually need a
Application
context reference on Android to use as indicated:
Copy code
val pref = KMMPreference(applicationContext)
What are you passing here for
applicationContext
?
p
That’s from androidMain. above i have sent.
j
I'm sorry I can't help you further if you can't understand and answer my question. Somewhere you are creating a
KMMPreference
object, passing it a
KMMContext
reference. On Android,
KMMContext
is typealiased to
Application
(specifically
android.app.Application
, which is an Android
Context
). When you construct
KMMPreference
, you are required to pass it a non-null
Application
Context
reference. Where are you getting this reference from? Again, this is in your code:
Copy code
val pref = KMMPreference(applicationContext)
Where is
applicationContext
coming from? The error you shared indicates that this reference is null, causing the crash.