Search code examples
androidandroid-studioandroid-databinding

Format friendly Date using android-databinding approach


I would like to format my date YYYY/MM/DD to more friendly mode.

I use android-databinding.

my expects output should be example: Tuesday, 22 August 2006. My Current input from Json is "2018-09-27" (String data in model)

my code:

public class DateUtils {

SimpleDateFormat fromServer = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat myFormat = new SimpleDateFormat("dddd, dd MMMM yyyy");

   public String getDateToFromat  (String reciveDate)  {
       String newFormatString = myFormat.format(fromServer.parse(reciveDate));
 return newFormatString;
   };

}

my layout:

<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data class ="CurrencyBindingDetailItem">
        <import type="com.example.htw.currencyconverter.utils.DateUtils"/>
        <import type="android.view.View" />
        <variable name="currencyItemDetailDate" type="com.example.htw.currencyconverter.model.CurrencyDate"/>
        <variable name="currencyBindingItemDetail" type="com.example.htw.currencyconverter.model.CurrencyBinding"/>
        <variable name="callback" type="com.example.htw.currencyconverter.callback.ClickCallback"/>
    </data>
    <TextView
        android:textSize="28dp"
        android:text="@{DateUtils.getDateToFromat(currencyItemDetailDate.date)}"
        android:textColor="@color/primary_text"
        android:id="@+id/date_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

and I do have error:

Found data binding errors.
****/ data binding error ****msg:**cannot find method getDateToFromat**(java.lang.String) in class com.example.htw.currencyconverter.utils.DateUtils

I did clean and restart and rebuild.


Solution

  • Why don't you create a databinding adapter, so your xml stays clearer? Since your date from the server is in string format, adapter will look like this:

    @BindingAdapter("bindServerDate")
    public static void bindServerDate(@NonNull TextView textView, String date) {
        /*Parse string data and set it in another format for your textView*/
    }
    

    The usage of it:

    In your viewModel create ObservableField<String> serverDate and set the value from your response, in xml set app:bindServerDate="@{viewModel.serverDate}". Don't forget to add viewModel as variable and set it from your activity/fragment