Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Database with ContentValue with boolean bug?

I created database table in my android app. I used this query:

CREATE TABLE foo (_id INTEGER PRIMARY KEY AUTOINCREMENT, mybool BOOLEAN)

Than I added row to the table, that the value of mybool will be true.
I ran the sqlite3 command to see the value in the table, and I saw:

  _id    |    mybool
----------------------
   1     |      1

That is corret, the true value became to 1.

The strange thing is in the reading. I read the table like that:

ContentValues values = new ContentValues();
Cursor cursor = db.rawQuery("SELECT * FROM foo", null);
DatabaseUtils.cursorRowToContentValues(cursor, values);

Then I get strange result:

values.getAsBoolean("mybool"); // return false - WRONG
values.getAsInteger("mybool"); // return 1 = true - CORRECT

I use the code like that to get boolean value:

values.getAsInteger("mybool") != 0; 

But it's strange.

Why I get always false in the getAsBoolean function? Is there any bug in the ContentValues class? Anyone else having this problem?

like image 346
nrofis Avatar asked Oct 26 '12 22:10

nrofis


2 Answers

DatabaseUtils.cursorRowToContentValues() stores everything as strings (except blobs). ContentValues.getAsBoolean() will attempt to convert the string to a boolean (using Boolean.valueOf()), but that only works if the string is equal to "true", not "1".

This looks like an Android bug to me.

like image 57
Zapek Avatar answered Nov 04 '22 00:11

Zapek


You've skipped some code here.

What's your proof that values.getAsBoolean("mybool") returns false? You have to return a Boolean. How are you checking it?

ContentValues.getAs returns a value if the key can be found, or null if it can't or if the value can't be converted. Be sure that you're doing a full test.

like image 1
Joe Malin Avatar answered Nov 04 '22 00:11

Joe Malin