Search code examples
androidsqliteandroid-sqlitestring.formatstrftime

String format in sqlite query


In my select query i am using string.format for the where clauses. When i have strfTime within format i am getting errors.

select = String.format(Locale.US, "SELECT %d AS %s, CAST(strftime('%s', START)  AS  integer) AS %s",
                    SORT_ID, SORT_ORDER_ID, SORT_ORDER_DATE);

// select = "SELECT " + SORT_ID + " AS SORT_ORDER_ID, CAST(strftime('%s', START) AS integer) AS SORT_ORDER_DATE";

The commented line without string.format works. But when i add string.format i am getting MissingFormatArgumentException: Format specifier '%s'


Solution

  • The format() function uses % as replacement markers; it expects a string for the %s in the call to strftime().

    But you don't want this to be replaced by format(). To get format() to output a single % character, you have to escape it by doubling it in the format string:

    String.format("... strftime('%%s', START) ...", ...);