Reputation: 539
I'm trying to make this function accessible from all files but if I define it outside class in Kotlin file, it shows me error for getSharedPreferences
as unresolved reference
. I think this is my answer but I don't know how to declare top-level function. How it can be done?
package com.example.app
fun retrieveData() {
val mypref = getSharedPreferences ("mypref", Context.MODE_PRIVATE)
val radiotext=mypref.getString("data","")
}
Upvotes: 0
Views: 309
Reputation: 517
I see two options:
package com.example.app
fun retrieveData(shPref: SharedPreferences): String {
val radioText = shPref.getString("data", "")
return radioText
}
package com.example.app
fun SharedPreferences.retrieveData(): String {
val radioText = this.getString("data", "")
return radioText
}
And you obviously need to get SharedPreference object beforehand to use this functions.
Upvotes: 1
Reputation: 93629
Declaring a top level function is as simple as not putting it within the braces { }
of a class declaration.
A SharedPreferences can only be retrieved from an Android Context. Make your function an extension of Context:
fun Context.retrieveData() { //...
Then you can use it from within any Context type object, such as calling it from some function inside your Activity. If calling it from a Fragment (which is not itself a Context object), you'd have to call it on a context: context.retrieveData()
.
Making it an extension function is just a way of rearranging how you call it. You could also define your function to take a Context argument:
fun retrieveData(context: Context) {
val mypref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE)
val radiotext=mypref.getString("data","")
}
In this case, you would always need to pass a Context. If you're in an Activity, you can pass this
or pass context
, which is a property of an Activity.
Upvotes: 2