Osama Omar
Osama Omar

Reputation: 119

How to save the value of a variable after initialization

I have a LiveData variable that increases it's value by 1 every time a user triggers certain events.

I want to save the value, so for example if the user triggered 1 event and closed the app and reopened it the variable value stays 1 instead of resetting to the initial value of 0 every time my ViewModel get recreated.

    private val counter = MutableLiveData<Int>().apply {
        value = 0
    }

    fun counterPlus(){
        counter.value = _counter.value!!.plus(1)
    }

Upvotes: 1

Views: 389

Answers (1)

Eddie Lopez
Eddie Lopez

Reputation: 1139

You want to save your data to persistent storage. There are three common options in Android: Files, SQLite database and SharedPreferences. For your use case, maybe SharedPreferences - which is a key-value type of storage mechanism - is a good option due to its simplicity.

Once you decide on that, the next step is to find a place/moment to save your data to the storage.

You could save in onPause and load in onResume for example, assuming you decide to go with SPs:

// In on pause
context.getSharedPreferences(...).edit().putInt("myValueKey", counter.value).apply();

To load, the procedure is very similar:

context.getSharedPreferences(...).getInt("myValueKey", defaultValue)

Check https://developer.android.com/training/data-storage/shared-preferences#kotlin

Upvotes: 1

Related Questions