为什么 SQLite 中 Android 游标的赋值返回 0 表示 true

Why is the assignment of Android cursor from SQLite returning 0 for true

我正在开发一个 Android 应用程序,在学习的同时,它访问一个 SQLite 数据库,该数据库在列中保存一些布尔数据(以及其他数据),但我对布尔数据的表示方式感到困惑.

据我了解,对于 SQLite 而言,0 为假,1 为真。这是我对我的问题的搜索所证明的(请参阅 get-boolean-from-database-using-android-and-sqlite and SQLite Docs 的两个示例)。

关于我的特殊问题,我正在查询的 table 有两个布尔列,并且在相关行中,这两个列此时都是 'true'。但是,当我在我的应用程序中分配这些列的值时,它们是 'false'。这是代码术语中的场景;

SQLiteDatabase db = getReadableDatabase();
String[] result_cols = new String[] { KEY, FD_CONTACT_FNAME, FD_CONTACT_SNAME, FD_IS_PUPIL, FD_IS_ACTIVE };
String where = KEY + " = ?";
String whereArgs[] = {id};
String groupBy = null;
String having = null;
String order = null;

Cursor cursor = db.query(DB_TABLE_CONTACTS, result_cols, where, whereArgs, groupBy, having, order);
Log.d("ACONTACT", DatabaseUtils.dumpCursorToString(cursor));

while (cursor.moveToNext()) {
    int three = cursor.getInt(3);
    int four = cursor.getInt(4);

    if (cursor.getInt(3) == 1) {
        Log.d("ONE", "1");
    } else if (cursor.getInt(3) == 0) {
        Log.d("ZERO", "0");
    }

    Contact mContact = new Contact(cursor.getLong(0), cursor.getString(1), cursor.getString(2), ((cursor.getInt(3) == 1)? true : false), (cursor.getInt(4) > 0));
    Log.d("ACONTACT", String.valueOf(mContact.getIsPupil()) + " .... " + String.valueOf(mContact.getIsActive()));
    Log.d("ACONTACT", String.valueOf(cursor.getInt(3)) + " .... " + String.valueOf(cursor.getInt(4)));
    Log.d("ACONTACT", cursor.getString(1) + " .... " + cursor.getString(2));
    Log.d("ACONTACT", String.valueOf(cursor.getLong(0)));
    return  mContact;
}

代码的日志记录方面导致;

D/ACONTACT: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@418c5f28
        0 {
           _id=24
           fname=Harry
           sname=Ballard
           is_pupil=true
           is_active=true
        }
        <<<<<
D/ZERO: 0
D/ACONTACT: false .... false
D/ACONTACT: 0 .... 0
D/ACONTACT: Harry .... Ballard
D/ACONTACT: 24

'Contact' 是一个自定义的 class,没什么复杂的,它有一个像这样的构造函数;

    public Contact( long id, String fname, String sname, Boolean isPupil, Boolean isActive ) {
    this.id = id;
    this.fname = fname ;
    this.sname = sname ;
    this.isPupil = isPupil;
    this.isActive = isActive;
}

我可以从日志中看到,光标在被 'DatabaseUtils' 转储时是正确的,但是当我读取光标值时,无论是进入我的 class 还是进入任何其他变量进行调试,它们看起来是错误的(例如,int 'three' 和 int 'four' 都保持为零,因此赋值后为 false)。其他三列中的数据始终正确。

我显然遗漏了一些东西,但正如我所见,游标保存了正确的数据(两个布尔列,都具有 'true' 的值,如游标转储所见)然后 cursor.getInt(3) 和 cursor.getInt(4) 都 return 为零,即错误。光标怎么会出现变化,它让我头疼:)

说了这么多,我的标题可能不准确,因为光标一开始是正确的,但后来出了问题。有人有什么线索吗?

documentation 表示 "Boolean values are stored as integers 0 (false) and 1 (true)" 时,这意味着:您必须将它们存储为数字 01.

目前,您正在数据库中存储 字符串 truefalse。这些值无法转换为整数。

好的,对于噪音,我深表歉意。使用文字值 'true' 和 'false' 将布尔数据插入到数据库中。因此,使用整数逻辑('cursor.getInt(0) > 0' 或等价物)确定 true 或 false 总是返回 false,因为保存的值实际上是 'true' 而不是 '1'。

我希望这很清楚。再次为噪音道歉。