Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/SQLite - Bit operation on WHERE clause

I'd like to know if it's possible to do in Android something like this:

public Cursor getFlowsByCategory(int type, int categoryID, int limit) {

    SQLiteDatabase db = dbHelper.getReadableDatabase();

    final String[] columns = {ID, FLAGS, SUBJECT, AMOUNT, AMOUNT_NO, CATEGORY};
    final String selection = "((" + FLAGS + " & ?) >> 1 = ?) AND (" + CATEGORY + " = ?)";
    final String[] selectionArgs = {Integer.toString(Flow.FLOW_TYPE), Integer.toString(type), Integer.toString(categoryID)};

    return db.query(TABLE, columns, selection, selectionArgs, null, null, ID + " DESC", Integer.toString(limit));

}

FLAGS is a 1-byte bit mask and I'd like to select only the rows which has the second bit (position 1) of the mask on. The mask (Flow.FLOW_TYPE) is 0b00000010 and the type parameter can be either 0 or 1. It should work but it doesn't: what am I doing wrong?

like image 491
Francesco Avatar asked Nov 03 '12 17:11

Francesco


1 Answers

The query function accepts only strings as parameters, but in SQLite, numbers and strings never compare equal (unless you have type affinity, but this works only for column values, not expressions).

You have to explicitly convert the parameters back to a number:

((...) >> 1 = CAST(? AS INTEGER)) AND ...
like image 163
CL. Avatar answered Sep 27 '22 21:09

CL.