如何獲取Android上的SQLite數據庫中布爾型字段的值?使用Android和SQLite從數據庫獲取布爾值
我通常使用getString()
,getInt()
等來獲取我的字段的值,但似乎沒有getBoolean()
方法。
如何獲取Android上的SQLite數據庫中布爾型字段的值?使用Android和SQLite從數據庫獲取布爾值
我通常使用getString()
,getInt()
等來獲取我的字段的值,但似乎沒有getBoolean()
方法。
是:
boolean value = cursor.getInt(boolean_column_index) > 0;
SQLite中沒有bool數據類型。使用您修復爲0或1的int來實現該效果。請參閱SQLite 3.0上的datatypes reference。
您還可以使用
boolean value =cursor.getString(boolean_column_index).equals("True");
equals()不包含 – 2013-10-11 18:16:50
boolean value = (cursor.getInt(boolean_column_index) == 1);
即使不完全對應這個問題(Alex's是最接近的),這是一個很好的答案,我會用這個。 – 2014-12-16 15:34:15
這裏大部分的答案可能會導致NumberFormatExceptions或 「運算符是不確定的各類空,INT」 如果您存儲int的列也被允許保留爲空。 體面的方式來做到這一點是使用
Boolean.parseBoolean(cursor.getString(booleanColumnIndex));`
雖然你現在僅限於存儲字符串「真」與「假」,而不是0或1
另一種選擇
boolean value = (cursor.getString(column_index)).equals("1");
在Ormlite Cursor找到的實現還檢查其他答案都沒有。
public boolean getBoolean(int columnIndex) {
if (cursor.isNull(columnIndex) || cursor.getShort(columnIndex) == 0) {
return false;
} else {
return true;
}
}
boolean b =(cursor.getInt(cursor.getColumnIndex(「item」))!= 0);
boolean
數據類型在Cursor
中不可用。
您將在int
中得到結果,因此您需要將該值轉換爲boolean
。
既可以使用
boolean b = cursor.getInt(boolean_column_index) > 0;
或
boolean b = (cursor.getInt(boolean_column_index) != 0);
cursor.getInt(boolean_column_index)!= 0 是更標準C. – Buttink 2014-02-28 21:53:56
@Buttink'> 0'是以字節爲單位更短雖然:P – 2017-02-09 14:52:54