使用Android和SQLite从数据库中获取布尔值

Kev*_*haw 166 java sqlite android boolean

如何在Android上的SQLite数据库中获取布尔字段的值?

我通常使用getString(),getInt()等来获取我的字段的值,但似乎没有getBoolean()方法.

Ale*_*lov 345

它是:

boolean value = cursor.getInt(boolean_column_index) > 0;
Run Code Online (Sandbox Code Playgroud)

  • cursor.getInt(boolean_column_index)!= 0更标准C. (29认同)
  • 但是@Buttink`> 0`的字节更短:P (2认同)

NG.*_*NG. 45

SQLite中没有bool数据类型.使用您修复为0或1的int来实现该效果.请参阅SQLite 3.0上的数据类型参考.


小智 21

boolean value = (cursor.getInt(boolean_column_index) == 1);
Run Code Online (Sandbox Code Playgroud)


Soj*_*urn 10

如果允许存储int的列也允许为null,则此处的大多数答案可能导致NumberFormatExceptions或"运算符未定义类型null,int".这样做的好方法就是使用

Boolean.parseBoolean(cursor.getString(booleanColumnIndex));`
Run Code Online (Sandbox Code Playgroud)

虽然您现在仅限于存储字符串"true"和"false"而不是0或1.

  • 这不起作用.Boolean.parseBoolean采用"true"或"false"字符串.如果您将布尔值存储为0或1,则总是会出错. (5认同)

小智 6

你也可以使用

boolean value =cursor.getString(boolean_column_index).equals("True");
Run Code Online (Sandbox Code Playgroud)

  • equals()不包含 (5认同)

rta*_*ack 6

Ormlite Cursor中找到的实现也检查Null,其他答案都没有.

   public boolean getBoolean(int columnIndex) {
        if (cursor.isNull(columnIndex) || cursor.getShort(columnIndex) == 0) {
            return false;
        } else {
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)