Mithun Sreedharan Mithun Sreedharan - 19 days ago 5
Android Question

How to write WHERE IN clause from a dymanic ArrayList for Android SQLite query

How can i write the where in clause in Android SQLite query?

Function to retrieve a single customer

public Cursor getCustomers(int groupId) {
return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME}, KEY_GROUP_ID+" = "+groupId, null, null, null, null);
}


Function to retrieve a more customers

public Cursor getCustomers(ArrayList<Integer> groupIds) {
// Need to apply SELECT id, name FROM customers WHERE id IN (11, 13, ...18);
//return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME}, KEY_GROUP_ID+" = "+groupIds, null, null, null, null);
}


The size of the groupId ArrayList is dynamic.

Answer
return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME }, KEY_GROUP_ID + " >=" + groupIdsLowLimit + " and " + KEY_GROUP_ID + " <=" + groupIdsUpLimit, null, null, null, null);

String where = "";
for (int i = 0; i < list.size(); i++) {
    where = where + KEY_GROUP_ID + " =" + list.get(i).toString() + "";
    if (i != (list.size() - 1))
        where = where + " or";
}

return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME }, where, null, null, null, null);