nro*_*fis 5 sqlite android boolean
我在我的Android应用程序中创建了数据库表.我用过这个查询:
CREATE TABLE foo (_id INTEGER PRIMARY KEY AUTOINCREMENT, mybool BOOLEAN)
Run Code Online (Sandbox Code Playgroud)
比我添加的行表,该值mybool会true.
我运行了sqlite3命令来查看表中的值,我看到:
_id | mybool
----------------------
1 | 1
Run Code Online (Sandbox Code Playgroud)
这是正确的,true价值变为1.
奇怪的是在阅读中.我这样读了桌子:
ContentValues values = new ContentValues();
Cursor cursor = db.rawQuery("SELECT * FROM foo", null);
DatabaseUtils.cursorRowToContentValues(cursor, values);
Run Code Online (Sandbox Code Playgroud)
然后我得到奇怪的结果:
values.getAsBoolean("mybool"); // return false - WRONG
values.getAsInteger("mybool"); // return 1 = true - CORRECT
Run Code Online (Sandbox Code Playgroud)
我使用这样的代码来获取布尔值:
values.getAsInteger("mybool") != 0;
Run Code Online (Sandbox Code Playgroud)
但这很奇怪.
为什么我总是false在这个getAsBoolean功能?ContentValues班上有没有错误?其他人有这个问题吗?
小智 6
DatabaseUtils.cursorRowToContentValues()将所有内容存储为字符串(blob除外).ContentValues.getAsBoolean()将尝试将字符串转换为布尔值(使用Boolean.valueOf()),但只有在字符串等于"true"而不是"1"时才有效.
对我来说,这看起来像是一个Android错误.
getAsBoolean不返回 a,boolean而是返回一个Boolean包装对象,该对象可以是null、Boolean.FALSE或Boolean.TRUE。如果您可以确保不存在NULLs,请使用values.getAsBoolean("mybool").booleanValue()来获取实际值。