The code is completely functional but I'd rather not call two functions when I know it can be done more efficiently. My goal is to store EditText values in SharedPrefs using a single addTextChangedListener. Any advice is much appreciated!
fun preserveText() {
val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
field_1.setText(sharedPref.getString("autoSave", ""))
field_1.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable) {
sharedPref.edit().putString("autoSave", s.toString()).apply()
}
})
}
fun preserveText2() {
val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
field_2.setText(sharedPref.getString("autoSave2", ""))
field_2.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable) {
sharedPref.edit().putString("autoSave2", s.toString()).apply()
}
})
}
field_1
orfield_2
as a parameter to the methodpreserveText
and create a link between those fields and the strings"autoSave"
and"autoSave2"
somewhere else, either through a map, or by making this string a field offield_1
/field_2
. \$\endgroup\$