代码之家  ›  专栏  ›  技术社区  ›  Kevin Bradshaw

使用Android和SQLite从数据库获取布尔值

  •  166
  • Kevin Bradshaw  · 技术社区  · 14 年前

    如何获取 SQLite Android上的数据库?

    getString() , getInt() ,等来获取我的字段的值,但似乎没有 getBoolean() 方法。

    9 回复  |  直到 9 年前
        1
  •  348
  •   Peter Mortensen icecrime    9 年前

    它是:

    boolean value = cursor.getInt(boolean_column_index) > 0;
    
        2
  •  45
  •   Peter Mortensen icecrime    9 年前

    SQLite中没有bool数据类型。使用您修正为0或1的int来达到这个效果。见 datatypes reference SQLite 3.0

        3
  •  22
  •   Elvis    13 年前
    boolean value = (cursor.getInt(boolean_column_index) == 1);
    
        4
  •  10
  •   Sojurn    11 年前

    这里的大多数答案可能会导致NumberFormatExceptions或“operator is undefined for the types null,int”,如果允许您存储int的列也包含null。 做这件事的好方法是

    Boolean.parseBoolean(cursor.getString(booleanColumnIndex));`
    

    尽管现在只能存储字符串“true”和“false”,而不是0或1。

        5
  •  6
  •   Szymon    11 年前

    Ormlite Cursor 同时检查空值,而其他答案都不检查空值。

       public boolean getBoolean(int columnIndex) {
            if (cursor.isNull(columnIndex) || cursor.getShort(columnIndex) == 0) {
                return false;
            } else {
                return true;
            }
        }
    
        6
  •  6
  •   AndyD273    10 年前

    你也可以使用

    boolean value =cursor.getString(boolean_column_index).equals("True");
    
        7
  •  3
  •   Gokhan Arik    12 年前

    另一种选择

    boolean value = (cursor.getString(column_index)).equals("1");
    
        8
  •  3
  •   Ravi    9 年前

    boolean Cursor .

    你会得到一个结果 int ,所以你需要转换 内景 布尔型 .

    你可以使用

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

    boolean b = (cursor.getInt(boolean_column_index) != 0);
    
        9
  •  2
  •   RedBullet    9 年前

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

        10
  •  0
  •   silexcorp    5 年前

    很简单:

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