3

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?

1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton, turns out I was a little off on my syntax with it, I'm super new to kotlin. When I type the first line, it says I have to pass a parameter for context for Parameter(). Do you know what I would pass for "context"? Thanks again
A Context see indirect subclasses -> your Activity -> inside the Actiity-class it is just this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.