How can I obtain the value of a boolean field in an SQLite database on Android?
I usually use getString()
, getInt()
, etc. to get the values of my fields, but 开发者_运维知识库there does not seem to be a getBoolean()
method.
It is:
boolean value = cursor.getInt(boolean_column_index) > 0;
There is no bool data type in SQLite. Use an int that you fix to 0 or 1 to achieve that effect. See the datatypes reference on SQLite 3.0.
boolean value = (cursor.getInt(boolean_column_index) == 1);
Most of the answers here can result in NumberFormatExceptions or "operator is undefined for the types null, int" if the column you stored the int in was allowed to also hold null. The decent way to do this would be to use
Boolean.parseBoolean(cursor.getString(booleanColumnIndex));`
though you are now limited to storing the strings "true" and "false" rather than 0 or 1.
An implementation found at Ormlite Cursor also checks for Null which none of the other answers do.
public boolean getBoolean(int columnIndex) {
if (cursor.isNull(columnIndex) || cursor.getShort(columnIndex) == 0) {
return false;
} else {
return true;
}
}
You can also use
boolean value =cursor.getString(boolean_column_index).equals("True");
boolean
datatype is not available in Cursor
.
you will get the result in an int
, so you need to convert that int
value to a boolean
.
You can either use
boolean b = cursor.getInt(boolean_column_index) > 0;
or
boolean b = (cursor.getInt(boolean_column_index) != 0);
Another option
boolean value = (cursor.getString(column_index)).equals("1");
boolean b = (cursor.getInt(cursor.getColumnIndex("item")) != 0);
Well, that's very simple:
public boolean getBooleanState(SQLiteDatabase db){
boolean result = false;
try{
String QUERY = "SELECT " + BOOLEAN_DATA + " FROM " + TABLE_NAME + " WHERE " + ID + " = 1";
Cursor cursor = db.rawQuery(QUERY, null);
if (cursor.moveToFirst()){
if(cursor.getString(0).equalsIgnoreCase("1")){
result = true;
}
}
c.close();
}catch(Exception ee){
Log.e(TAG, "err getBooleanState: " + TABLE_NAME );
}
return result;
}
For an optional (nullable) Boolean stored as INTEGER
, you can create a Kotlin extension:
fun Cursor.getBoolean(columnIndex: Int): Boolean? {
return if (isNull(columnIndex))
null
else
getInt(columnIndex) != 0
}
and use it like this:
val value: Boolean? = cursor.getBoolean(boolean_column_index)
thats what I used:
val work = Work()
work.id = cursor.getInt(0)
work.date = cursor.getString(1)
work.work_value = cursor.getFloat(2)
work.place = cursor.getString(3)
work.wind = cursor.getFloat(4)
work.isCompetition = cursor.getInt(5) > 0
return work
I face the same thing in kotlin. There was the value "true/false" in the database and I access it with this code:
cursor.getString(4).toBoolean()
//first as a string then converting them to boolean
精彩评论