I am trying to use two-way databinding on a EditText. String values are working fine but I can't get it working for Float values.
I have tried to use a binding adapter that I found in this answer with no luck: Android DataBinding float to TextView
Then I found this Converter class on the android developers website. https://developer.android.com/topic/libraries/data-binding/two-way#kotlin
public class Converter {
@InverseMethod("stringToFloat")
public static String floatToString(float value) {
try {
return String.valueOf(value);
} catch (Exception e) {
return "";
}
}
public static float stringToFloat(String value) {
try {
return Float.parseFloat(value);
} catch (Exception e) {
return 0.0f;
}
}
}
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/width"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Width"
android:inputType="number"
android:text="@={Converter.floatToString(product.width)}"/>
data class Product(
val height: Float?,
val length: Float?,
val width: Float?,
val weight: Float?,
): BaseObservable() {
After using the converter class I get the following error when compiling:
error: cannot generate view binders java.lang.NullPointerException at android.databinding.tool.expr.Expr.lambda$join$0(Expr.java:771)