I'm attempting to load and save data using sharedpreferences in Kotlin, specifically using the Android Studio.
I'm getting this error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
Pointing at my initialization of shared preferences.
class MainActivity : AppCompatActivity(), SensorEventListener {
private val dragonstats by lazy {getSharedPreferences("DRAGON_STATS",Context.MODE_PRIVATE)}
I get the same error if I write it this way:
val dragonstats = getSharedPreferences("DRAGON_STATS", Context.MODE_PRIVATE)
I've seen in other answers to declare it this way:
SharedPreferences dragonstats
but that doesn't read in Kotlin.
The android.com file on Shared preferences says to declare it this way:
val sharedPref = activity?.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE)
but that gives an unresolved reference error on activity.
How do I initialize a SharedPreferences file so I can store and retrieve data in Kotlin?
EDIT: So, the only thing that has worked to get it functional is to put ? in everything.
I declare it outside of oncreate so I can use it throughout:
var dragonstats: SharedPreferences? = null
in oncreate I set it:
dragonstats = PreferenceManager.getDefaultSharedPreferences(this)
Then, when I want to call any piece of it, I use ?:
exerciselevel = dragonstats?.getInt("exerciselevel", 0)!!
I don't understand why this works but nothing else does.