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.