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.
You can use the Android TextUtils class join method to make a comma separated list of IDs to put in the in clause.
String selection = KEY_GROUP_ID + " IN (" + TextUtils.join(", ", groupIds) + ")";
return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME}, selection, null, null, null, null);
BTW if groupIds is a list of primary keys from another table you should be using Longs to store them not Integers otherwise it will overflow when the IDs get large.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With