I have got a Preference with the key "base_url" with an onPreferenceChangeListener. The problem is that I want to change wrong input directly in the onPreferenceChange but it does not save. For example: Input is google.at it should add https:// to the URL.
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings_pref, rootKey)
val editURLPreference: EditTextPreference? = findPreference("base_url")
val preferenceURLListener: Preference.OnPreferenceChangeListener =
object : Preference.OnPreferenceChangeListener {
override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
var newURL = newValue as String
when {
newURL.isEmpty() -> {
}
newURL.startsWith("https://") -> {
}
newURL.startsWith("http://") -> newURL =
newURL.replace("http://", "https://")
else -> newURL = "https://".plus(newValue)
}
if (Patterns.WEB_URL.matcher(newURL).matches()) {
Log.w("Test","passt $newURL")
val sharedPref = PreferenceManager.getDefaultSharedPreferences(requireContext().applicationContext)
sharedPref.edit().putString("base_url",newURL).apply()
Log.w("Test",sharedPref.getString("base_url","")) //This works!
removeFiles()
return true
}
Toast.makeText(context, "Ungültige Eingabe", Toast.LENGTH_LONG).show()
return false
}
}
editURLPreference?.onPreferenceChangeListener = preferenceURLListener
The problem is that when I am trying to call the preference in an Activity it displays the old value without https:// This is my call in MainActivity:
override fun onResume() {
super.onResume()
Log.w("baseURL",PreferenceManager.getDefaultSharedPreferences(applicationContext).getString("base_url",""))
}
I think the problem is that the new Value is not saved correctly, i know that true will accept newValue maybe it overrides the correct value. (I have tried it with context and applicationcontext.)
Because calling the Preference directly in the onPreferenceChangeListener gives the correct output with https.
sharedPref.getString("base_url","")
I think there are a couple of problems here:
true
, the current value in the preference (newValue
) will be saved to the SharedPreferences
. This will overwrite the value you have manually saved.So instead, swap the true
and false
, so when you want to 'intercept' the change you return false, and if you leave the value unchanged you return true. And then instead of manually changing the shared preferences, call preference.setText(newURL)
. This will update the shared preferences, and notify the preference that the value has changed, so it will update on screen.