I have a class that takes user inputs in a text field and converts them to an any class using the supplied functions
class GenericTextFieldDelegate<T>(
private val initBlock: () -> TextView,
private val getConversion: (String?) -> T?,
private val setConversion: (T?) -> String? = { it?.toString() }
) {
private val textView: TextView by lazy { initBlock() }
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? =
getConversion(textView.text?.toString())
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
textView.text = setConversion(value)
}
}
I have done this so that when I have TextViews I can do this
class IntegerInputView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attributeSet, defStyleAttr), DataInput<Int> {
override var value: Int? by GenericTextFieldDelegate(
{ inputET },
getConversion = { it?.toIntOrNull() },
setConversion = { it.toString() }
)
...
I have a fragment that has an above custom view and when I have
override var tareWeight: Kg?
get() = tareWeightInput.value
set(value) {
tareWeightInput.value = value
}
all works fine, by what I really want to do is
override var tareWeight: Kg? by tareWeightInput
adding these lines to IntegerInputView
...
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int? = value
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int?) {
this.value = value
}
override var value: Int? by GenericTextFieldDelegate(
...
When I build, run and load the fragment this I get the below stack trace. Where am I going wrong?
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Integer com.gameforeverything.storekeeper.customViews.IntegerInputView.getValue(java.lang.Object, kotlin.reflect.KProperty)' on a null object reference
at com.gameforeverything.storekeeper.fragments.weighInFragment.WeighInFragment.getGrossWeight(Unknown Source:7)
at com.gameforeverything.storekeeper.fragments.weighInFragment.WeighInPresenter.getNetWeight(WeighInPresenter.kt:40)