Search code examples
androidandroid-layoutandroid-databinding

Android DataBinding showing merged string with null check not working


I need to have show merged string through data binding. I can able to show it by below code easily.

android:text='@{sentRequestItems.receiver.firstName + " " + sentRequestItems.receiver.lastName}'

But in some case their is possibility that last name getting null form API response so in that case i can not able to show last name with null check.

I am trying with below code.

android:text='@{sentRequestItems.receiver.firstName != null ? sentRequestItems.receiver.firstName : "" + " " + sentRequestItems.receiver.lastName != null ? sentRequestItems.receiver.lastName : ""}'

Here with this it is not showing last name when it is not null in API response.

<androidx.appcompat.widget.AppCompatTextView
      android:id="@+id/txvContactName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentStart="true"
      android:layout_marginStart="@dimen/_8sdp"
      android:layout_marginEnd="@dimen/_4sdp"
      android:layout_toStartOf="@+id/ivCancelRequest"
      android:fontFamily="@font/lato_bold"
      android:text='@{sentRequestItems.receiver.firstName != null ? sentRequestItems.receiver.firstName : "" + " " + sentRequestItems.receiver.lastName != null ? sentRequestItems.receiver.lastName : ""}'
      android:textColor="@color/black"
      android:textSize="@dimen/_15ssp"
      tools:text="John Donny">

Any help is greatly appreciated.


Solution

  • I think it's not a best idea to perform coding in xml, readability suffers. I suggest you to create static method, something like

    class Utils {
      static String formatName(RequestItem sentRequestItems) {
         return (sentRequestItems.receiver.firstName != null ? 
                 sentRequestItems.receiver.firstName : "") + " " + 
                 (sentRequestItems.receiver.lastName != null ? sentRequestItems.receiver.lastName : "")
      }
    }
    

    It's simplier to debug. Also, don't forget brackets. You code doesn't work, because if first comparison sentRequestItems.receiver.firstName != null succeeds, all expression just returns sentRequestItems.receiver.firstName.

    then in import it in your xml and use, like

    android:text="@{Utils.formatName(sentRequestItems)}"