Get boolean from database using Android and SQLite

后端 未结 10 1459
情话喂你
情话喂你 2020-12-07 09:02

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

相关标签:
10条回答
  • 2020-12-07 09:59

    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;
            }
        }
    
    0 讨论(0)
  • 2020-12-07 09:59

    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);
    
    0 讨论(0)
  • 2020-12-07 10:01

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

    0 讨论(0)
  • 2020-12-07 10:02

    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;
    }
    
    0 讨论(0)
提交回复
热议问题