Home » Android » java – Get boolean from database using Android and SQLite

java – Get boolean from database using Android and SQLite

Posted by: admin March 10, 2020 Leave a comment

Questions:

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.

How to&Answers:

It is:

boolean value = cursor.getInt(boolean_column_index) > 0;

Answer:

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.

Answer:

boolean value = (cursor.getInt(boolean_column_index) == 1);

Answer:

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.

Answer:

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

Answer:

You can also use

boolean value =cursor.getString(boolean_column_index).equals("True");

Answer:

Another option

boolean value = (cursor.getString(column_index)).equals("1");

Answer:

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

Answer:

boolean b = (cursor.getInt(cursor.getColumnIndex(“item”)) != 0);

Answer:

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