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
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;
}
}
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);
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;
}