Answer the question
In order to leave comments, you need to log in
Why does the application crash because of the sharedPreferences change handler?
There is an Activity -> there are 3 fragments in it -> in one of the fragments I call DialogFragment
// Вызываю класс диалога
binding.editUserProfile.setOnClickListener {
dialogEditUser.show(childFragmentManager, "DialogUserEdit")
}
class ViewModelUser(application: Application) : AndroidViewModel(application),
SharedPreferences.OnSharedPreferenceChangeListener {
val sharedPreferencesHelper: SharedPreferencesHelper by lazy {
SharedPreferencesHelper(getApplication())
}
val liveDataName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
val liveDataWeight: MutableLiveData<Float> by lazy {
MutableLiveData<Float>()
}
init {
liveDataName.value = sharedPreferencesHelper.getUserName()
liveDataWeight.value = sharedPreferencesHelper.getUserWeight()
// sharedPreferencesHelper.preferenceUser.registerOnSharedPreferenceChangeListener(this)
}
// set data from dialogUserEdit to LiveData
override fun onSharedPreferenceChanged(preferences: SharedPreferences?, key: String?) {
when(key) {
SharedPreferencesHelper.KEY_NAME_USER ->
liveDataName.value = sharedPreferencesHelper.getUserName()
SharedPreferencesHelper.KEY_WEIGHT_USER ->
liveDataWeight.value = sharedPreferencesHelper.getUserWeight()
}
}
override fun onCleared() {
sharedPreferencesHelper.preferenceUser.unregisterOnSharedPreferenceChangeListener(this)
super.onCleared()
}
}
// save data in dialog
bindingDialog.saveEditsButton.setOnClickListener {
val userWeight = bindingDialog.weightEditSlider.value
val userName = bindingDialog.nameEditInput.editText?.text.toString()
// просто запись в sharedPreferences через класс live Data
liveDataUser.sharedPreferencesHelper.setUserWeight(userWeight)
liveDataUser.sharedPreferencesHelper.setUserName(userName)
dismiss()
}
// Беру начальные значения из LiveData, которые взяли значения из sharedPrefrences
liveDataUser.liveDataName.observe(requireActivity()) {
bindingDialog.nameEditInput.editText?.setText(it)
}
liveDataUser.liveDataWeight.observe(requireActivity()) {
bindingDialog.finalWeight.text = "${getString(R.string.weight)} $it"
bindingDialog.weightEditSlider.value = it
}
// set data from dialogUserEdit to LiveData
override fun onSharedPreferenceChanged(preferences: SharedPreferences?, key: String?) {
when(key) {
SharedPreferencesHelper.KEY_NAME_USER ->
liveDataName.value = sharedPreferencesHelper.getUserName()
SharedPreferencesHelper.KEY_WEIGHT_USER ->
liveDataWeight.value = sharedPreferencesHelper.getUserWeight()
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question