Get boolean from database using Android and SQLite
JavaAndroidSqliteBooleanJava Problem Overview
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.
Java Solutions
Solution 1 - Java
It is:
boolean value = cursor.getInt(boolean_column_index) > 0;
Solution 2 - Java
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.
Solution 3 - Java
boolean value = (cursor.getInt(boolean_column_index) == 1);
Solution 4 - Java
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.
Solution 5 - Java
You can also use
boolean value =cursor.getString(boolean_column_index).equals("True");
Solution 6 - Java
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;
}
}
Solution 7 - Java
Another option
boolean value = (cursor.getString(column_index)).equals("1");
Solution 8 - Java
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);
Solution 9 - Java
boolean b = (cursor.getInt(cursor.getColumnIndex("item")) != 0);
Solution 10 - Java
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;
}
Solution 11 - Java
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)
Solution 12 - Java
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