I use AutoclearedValue in android, and in my old tablet which runs Android 4.4.4 I always get an exception like this: should never call auto-cleared-value get when it might not be available from AutoclearedValue class
I dont understand why, bacause in newer devices I don't get this exception.
The scenario is the following: I click an item in recyclerview, than an another fragment will open. In this fragment I implemented simple scrollview listener, it works perfectly. When I click back button, to navigate back to the previous fragment, then I get the exception.
My AutoClearedValue class:
class AutoClearedValue<T : Any>(val fragment: Fragment) : ReadWriteProperty<Fragment, T> {
private var _value: T? = null
init {
fragment.lifecycle.addObserver(object: DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner ->
viewLifecycleOwner?.lifecycle?.addObserver(object: DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
_value = null
}
})
}
}
})
}
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
return _value ?: throw IllegalStateException(
"should never call auto-cleared-value get when it might not be available"
)
}
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) {
_value = value
}
}
/**
* Creates an [AutoClearedValue] associated with this fragment.
*/
fun <T : Any> Fragment.autoCleared() = AutoClearedValue<T>(this)
And my listener where the exception comes from:
private fun initListeners() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
binding.freightTaskRowDetailScrollView.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->
if (binding.showFab == true) {
if (scrollY <= oldScrollY) {
if (!binding.expandableFab.isShown)
binding.expandableFab.showHide()
} else {
if (binding.expandableFab.isShown)
binding.expandableFab.showHide()
}
}
}
} else {
binding.freightTaskRowDetailScrollView.viewTreeObserver
.addOnScrollChangedListener {
if (binding.showFab == true) { [this line]
if (!binding.freightTaskRowDetailScrollView.canScrollVertically(1)) {
if (binding.expandableFab.isShown)
binding.expandableFab.showHide()
}
if (!binding.freightTaskRowDetailScrollView.canScrollVertically(-1)) {
if (!binding.expandableFab.isShown)
binding.expandableFab.showHide()
}
}
}
}
}