Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function from one class in another class in Android Studio [Kotlin]?

Tags:

android

kotlin

I am trying to save user preferences for language, so I have a preferences class with a setter and getter for language, as well as a separate Language activity where the user actually picks which language they want.

From this language activity, I want to use the setter to set the user's chosen language preference within the preferences class. Here is the preferences class:

class Preferences (context: Context) {
    val PREFS_FILENAME = "artour.prefs"
    val LANGUAGE = "language"
    val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE);

    fun getLang() : String {
        return prefs.getString(LANGUAGE, "english")
    }

    public fun setLang(lang:String) {
        val editor = prefs.edit()
        editor.putString(LANGUAGE, lang)
        editor.apply()
    }
}

How would I go about running the setLang method from the language activity?

like image 289
Lassley Avatar asked Jan 22 '26 04:01

Lassley


1 Answers

I dont now if I'm missing anything in this question, but just do this:

val preferences = Preferences(this)
preferences.setLang("it is that easy")

in any function in your activity class.

What it does is create an object (val preferences = Preferences()) and then calling a method on it (preferences.setLang("this is a string")).
Make sure to use an actual language identifier instead of a random string though.

like image 187
leonardkraemer Avatar answered Jan 23 '26 20:01

leonardkraemer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!