androidkotlinsharedpreferences

How to put an init value into preference data store in android Kotlin


I want to save user settings into preference data store.

Here is my code:

class SettingsRepository {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_settings")

    suspend fun saveSetting(context: Context, data: String, settingKey: String) {
        val dataStoreKey = stringPreferencesKey(settingKey)
        context.dataStore.edit { settings ->
            settings[dataStoreKey] = data
        }
    }

    suspend fun getSetting(context: Context, settingKey: String): String? {
        val dataStoreKey = stringPreferencesKey(settingKey)
        val preferences = context.dataStore.data.first()
        return if (preferences[dataStoreKey] != null) {
            preferences[dataStoreKey]
        } else {
            null
        }
    }

    companion object {
        const val WIND_SPEED_UNIT = "wind_sp_unit"
        const val VISIBILITY_UNIT = "visibility_unit"
        const val PRESSURE_UNIT = "pressure_unit"
        const val TEMPERATURE_UNIT = "temperature_unit"
    }
}

I don't know how to set an initial value for the preference data store. I want my app to use default settings when the user launches it for the first time. For example, I want the default wind speed unit to be km/h, and if the user wants to change the unit, the new value will be stored.

I'm looking forward for any advice or suggestion. Thank you


Solution

  • A super simple and production ready way to do this is a small modification to your code:

    return if (preferences[dataStoreKey] != null) {
        preferences[dataStoreKey]
    } else {
        preferencesDefaults[dataStoreKey] // previous: null
    }
    

    And then define the map of defaults above:

    val preferencesDefaults = mapOf(“windSpeed” to "15", “humidity” to "31.4", “userName” to "Bob”)
    

    Once a new custom value is saved then an individual value will no longer be null in the db and the default is ignored. To check if a default is being used you can have a function to check for null for a key. To dynamically initialize this map can come from the backend and be different per region.

    A bonus is your function will never return null!