Search code examples
javaandroidsqliteandroid-sqliteandroid-cursor

Why the sqlite cursor in android returns different values?


I have simple query, where you can see a row:

SELECT substr(..., 10, 6) as X

If I use cursor.getInt(...) I get 1048 (the "wrong" value)

If I use cursor.getString(...) I get "002030" (which is correct).

So, what makes sqlite parse "002030" as 1048?

Do I have to get it as string and parse it myself every time?

Thank you.


Solution

  • The function substr() returns a string, so you should retrieve the value with cursor.getString(), which returns the correct result.

    If you want the result as an integer, you must convert it in your sql code, either explicitly:

    SELECT cast(substr(..., 10, 6) as integer) as X 
    

    or implicitly:

    SELECT substr(..., 10, 6) + 0 as X
    

    The result will be the integer 2030 without the leading 0s.

    As for the strange 1048 that you get, Java considers numeric literals starting with 0 as octal numbers, so:

    int x = 002030;
    

    assigns 1048 to x which is the decimal representation of the octal number 2030.