Search code examples
kotlintoplevelextension-function

How to define top-level function with sharedPreferences inside?


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","")
    }

Solution

  • 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.