I am trying to find a way to have threaded messaging in my app so I want to scan the database for messages that have the same two people as receivers and senders, for example: find all messages from Jack to Steve and from Steve to Jack and combine them in a threaded message view that has the messages sorted naturally by the primary key _id. At least that's how I think of doing it.
While trying to retrieve all the messages by a receiver, I have this method:
public ArrayList<Message> retrieveMessageFromReceiver(String email) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Message> messages = new ArrayList<Message>();
Cursor cursor = db.query(TABLE_MESSAGES, new String[] { COLUMN_ID_M,
COLUMN_SENDER_M, COLUMN_RECEIVER_M, COLUMN_CONTENT_M,
COLUMN_TIMESTAMP_M, COLUMN_VISIBLE_TO_SENDER,
COLUMN_VISIBLE_TO_RECEIVER, COLUMN_READ_STATUS },
COLUMN_RECEIVER_M + "=?", new String[] { email }, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
Message message = new Message(Integer.parseInt(cursor
.getString(0)), cursor.getString(1),
cursor.getString(2), cursor.getString(3),
cursor.getString(4), Integer.parseInt(cursor
.getString(5)), Integer.parseInt(cursor
.getString(6)), Integer.parseInt(cursor
.getString(7)));
messages.add(message);
} while (cursor.moveToNext());
}
return messages;
}
Now, can I modify the query() statement to something like:
Cursor cursor = db.query(TABLE_MESSAGES, new String[] { COLUMN_ID_M,
COLUMN_SENDER_M, COLUMN_RECEIVER_M, COLUMN_CONTENT_M,
COLUMN_TIMESTAMP_M, COLUMN_VISIBLE_TO_SENDER,
COLUMN_VISIBLE_TO_RECEIVER, COLUMN_READ_STATUS }, "("
+ COLUMN_RECEIVER_M + "=?" + " AND " + COLUMN_SENDER_M + "=?"
+ ")" + " OR " + "(" + COLUMN_SENDER_M + "=?" + " AND "
+ COLUMN_RECEIVER_M + "=?" + ")", new String[] { email1,
email2, email1, email2 }, null, null, null, null);
..so that the SQL syntax is "(receiver = ? AND sender = ?) OR (sender = ? AND receiver = ?)"? Obviously, I'd need to change the method arguments so that it accepts two arguments (email1 and email2).
I guess what I'm asking is: can the WHERE selectionArgs arguments correspond to as many "?"s in the selection string as I want? (four in this case). Does the grouping of the operators this way: " (? AND ?) OR (? AND ?) " have any effect on what I'm trying to achieve? Or am I going completely the wrong way about this?