Sergio76
Sergio76

Reputation: 3986

Saving values ​in SharedPreference from my model class with Kotlin

I have a question that I think is pretty basic.

I'm doing my model class on a test application at Kotlin.

This is my code:

class Persona(name :String, age :Int) {

    val CUSTOM_PREF_NAME = "App_data"
    val prefs = customPreference(MainApplication.applicationContext(), CUSTOM_PREF_NAME)

    var name :String = name
        get() = "The name: $field" 
        set(value) {
            prefs.saveName = value
        }

    var age: Int = age
        get() = field
        set(value) {
          field = value
        }
}

What I want is that between the brackets of the var name set, the value is saved in SharedPreferences.

I didn't succeed and I think I got the theory wrong.

In the brackets of the set I couldn't even execute a simple log.

I can't run anything from there? How would I save a value in SharedPreferences from the set? Using sharedPreferences from any other point in the app works fine,.

I think I'm a little lost here.

Thanks in advance.

Upvotes: 0

Views: 166

Answers (1)

damienG
damienG

Reputation: 444

    var name :String = name
    get() = "The name: $field" 
    set(value) {
        field = value
        prefs.saveName = value
    }

Upvotes: 1

Related Questions