Search code examples
androiddata-bindingandroid-databinding

Data Binding giving NullPointerException when used with static method


I am getting a NullPointerException when I use to format date with my StringUtils class. If I use it without StringUtils, it just works fine.

I have added the import statement for StringUtils

I have this:

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="@{StringUtils.getFormattedDate(user.date)}" />

This gives me an error in my StringUtils method:

public static String getFormattedDate(String unformattedDate) {
        // unformattedDate will be in format of yyyy-mm-dd
        // Convert it to d mmm, yyyy
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = null;
        try {
            Date d = df.parse(unformattedDate);   // <<--------- Here
            SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM, yyyy");
            date = dateFormat.format(d.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

When I checked with debugger, unformattedDate is null from the beginning. The correct method is called but the value passed is null. This is strange.

When I use it like this in the layout file:

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="@{user.date}" />

It gives me no error, and date is displayed on screen!

I have tried cleaning the project and re-run it. But no success.


Solution

  • Data bindings are null-safe itself, but this doesn't hold for using the values as parameter. Since the getFormattedDate() is yours to change, just make sure it's null-safe as well. You're already returning null if there's a ParseException anyway.

    public static String getFormattedDate(String unformattedDate) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d = df.parse(unformattedDate);
            SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM, yyyy");
            return dateFormat.format(d.getTime());
        } catch (Exception e) {
            Log.w("StringUtils", "getFormattedDate", e);
            return null;
        }
    }