https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
p

Praveen Kumar

07/11/2023, 6:25 AM
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

Jeff Lockhart

07/11/2023, 6:40 AM
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

Praveen Kumar

07/11/2023, 6:41 AM
Copy code
actual typealias KMMContext = Application
here
j

Jeff Lockhart

07/11/2023, 6:47 AM
Where are you getting your
applicationContext
reference you're passing here?
Copy code
val pref = KMMPreference(applicationContext)
p

Praveen Kumar

07/11/2023, 9:09 AM
Copy code
actual typealias KMMContext = Application
here, this is from
j

Jeff Lockhart

07/11/2023, 6:55 PM
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

Praveen Kumar

07/12/2023, 6:26 AM
That’s from androidMain. above i have sent.
j

Jeff Lockhart

07/12/2023, 7:15 AM
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.
2 Views