androidkotlinsharedpreferencespreferenceactivity

How to format value in onPreferenceChangeListener before saving?


I have an EditTextPreference in my PreferenceScreen in the field i have to save the user have to input a valid URL and as that url will be used for retrofit calls i have to format it properly.

So i've created a onPreferenceChangeListener where initially i check if the url insert is valid and then i'm formatting it.

The issue is that once the user press ok the formatted value is not saved, no value is saved at all.

Here is my listener:

private fun String.formatURL(): String {
    var url = this

    if (!this.startsWith("http")) {
        url = "http://$url"
    }

    if (!url.endsWith("/")) {
        url = "$url/"
    }

    return url
}

editPref?.onPreferenceChangeListener =
    Preference.OnPreferenceChangeListener { preference, newValue ->
        val url = newValue.toString()
        if (Patterns.WEB_URL.matcher(url).matches()) {
            preference.sharedPreferences.edit().putString(preference.key, url.formatURL())
            false
        } else {
            customSnack(requireView(), "URL del server non valido!", true)
            false
        }
    }

Solution

  • note that OnPreferenceChangeListener return true/false if value can be stored or not. you are returning false even whe URL matches pattern. you should return true then

        if (Patterns.WEB_URL.matcher(url).matches()) {
            preference.sharedPreferences.edit().putString(preference.key, url.formatURL())
            true // proper URL, storing, handled
        } else {
            customSnack(requireView(), "URL del server non valido!", true)
            false
        }