SQLite CursorLoader selection parameter - date format the column

63 views Asked by At

In my android app I have a database that stores dates as long values from System.currentTimeInMilis. I now want to query specific days using a CursorLoader. This is what I have tried:

DateFormat sameDayCheckerformatter = new SimpleDateFormat("dd-MM-yyyy");

String selection = sameDayCheckerformatter.format(ItemEntry.COLUMN_DAY) + "=" + sameDayCheckerformatter.format(dayInMilis);

return new CursorLoader(getActivity(),
            ItemContract.ItemEntry.CONTENT_URI_ITEMS,
            projection,
            selection,
            null,
            null);

This did not work as I expected:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

But I can not find a solution. How do I solve this?

1

There are 1 answers

2
forpas On BEST ANSWER

Why do you apply format to ItemEntry.COLUMN_DAY?
It looks like a String representing a column name.
Also you need to surround the formatted date with quotes.
Change to this:

String selection = ItemEntry.COLUMN_DAY + " = '" + sameDayCheckerformatter.format(dayInMilis) + "'";

Edit: If the column ItemEntry.COLUMN_DAY has integer values then you don't need to format at all:

String selection = ItemEntry.COLUMN_DAY + " = "  + dayInMilis;

Edit 2: You need strftime() function:

String selection = 
    "strftime('%d-%m-%Y', " + ItemEntry.COLUMN_DAY + " / 1000, 'unixepoch') = '" + 
    sameDayCheckerformatter.format(dayInMilis) + "'";