ContentValues 类包含一个允许将布尔值放入值集合中的方法。 AFAIK,SQLite 不包含 Android 可以将布尔值推入的原生布尔格式。那么,Android 在幕后使用什么魔法来存储这些值呢?
另外,为什么游标上没有免费的 getBoolean 方法?对我来说,这似乎是一个相当尴尬的设计疏忽,因为似乎没有“安全”的方法来检索通过 ContentValues 放入数据库的布尔值。我缺少什么?
这个问题可能看起来有点无聊,因为我怀疑布尔值存储为 1 或 0 整数,但为什么 Android 会要求开发人员做出这样的假设呢?据我所知,它甚至没有记录。
The ContentValues class contains a method that allows Booleans to be put into the values collection. AFAIK, SQLite does not contain a native Boolean format that Android could push the boolean values into. So, what magic does Android do behind the scenes to store these values?
Also, why is there no complimentary getBoolean method on a Cursor? To me, this appears to be a pretty awkward design oversight since there seems to be no "safe" way of retrieving a boolean value that was put into the DB via ContentValues. What am I missing?
This question may seem a bit frivolous since I suspect that the boolean's are stored as a 1 or 0 integer, but why would Android commit to developers making that assumption? Its not even documented as far as I am aware.
发布评论
评论(2)
从阅读 this 文档来看,听起来布尔到整数的转换是由 SQLite 完成的。
如果您正在从游标中读取数据,那么您就知道应该从查询中返回哪些列,因此您大概知道所请求的列的数据类型。我同意使用
getBoolean
方法会更好,但这并不难解决。From reading this document, it sounds like the boolean to integer conversion is done by SQLite.
If you're reading from a cursor, then you know what columns should be returned from the query, so you presumably know the data types of the columns that were requested. I agree that having a
getBoolean
method would be better, but it's not hard to work around.更新
谷歌已经修补了前面提到的错误,尽管在本文发表时尚未实现:
https://code.google.com/p/android/issues/detail?id=232274
值得注意的是,当前的 API 很危险,如果底层发生任何变化,可能会破坏您的应用程序。
此外,
ContentValues.getBoolean
有一个主要问题,如果您使用DatabaseUtils.cursorRowToContentValues
创建ContentValues
,它会将每个字段视为字符串:< code>values.put(columns[i],cursor.getString(i));
当您通过
ContentValues.getBoolean
检索该字段时,您将始终得到 false:因为 value 是 " 0”或“1”此转换失败:
因此我强烈建议您创建自己的 getter 和 setter,以便明确定义您的行为。
UPDATE
Google has patched the previously mentioned bug, though it's not implemented yet at the time of this post:
https://code.google.com/p/android/issues/detail?id=232274
It's worth noting that the current API is dangerous and could break your app if anything changes under the hood.
Additionally,
ContentValues.getBoolean
has a major issue that if you create theContentValues
withDatabaseUtils.cursorRowToContentValues
it will treat EVERY field as a string:values.put(columns[i], cursor.getString(i));
When you then retrieve the field via
ContentValues.getBoolean
you will ALWAYS get false:Since value is "0" or "1" this conversion fails:
So I highly recommend that you create your own getter and setter so your behavior is well defined.