Android Data Binding @BindingConversion failure for int to string

Dave picture Dave · Jun 16, 2016 · Viewed 29.5k times · Source

Ran into a mysterious problem when trying to make a @BindingConversion for int to string.
The following code works for floats to strings:

xml:

...
<variable
        name="myViewModel"
        type="... .SomeModel" />
...
<TextView
            style="@style/StyleStuff"
            android:text="@{myViewModel.number}" />

code:

public class SomeModel {
    public ObservableFloat number = new ObservableFloat();
}

and setting:

viewModel.number.set(3.14f);

But if I try the same thing for ints to strings I get a crash.

 public ObservableInt number = new ObservableInt();

with

viewModel.number.set(42);

I get the following:

FATAL EXCEPTION: main
Process: ...myapplication, PID: 14311
android.content.res.Resources$NotFoundException: String resource ID #0xfa0
    at android.content.res.Resources.getText(Resources.java:1123)
    at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
    at android.widget.TextView.setText(TextView.java:4816)
    at ...executeBindings(ActivityAdaptersBinding.java:336)
    at android.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:355)

Any ideas? Thanks!

Answer

CommonsWare picture CommonsWare · Jun 16, 2016

android:text with an int assumes that the int is a string resource ID. Use android:text="@{Integer.toString(myViewModel.number)}".

You will also need to import the Integer class: (no longer needed)