Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write WHERE IN clause from a dynamic 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.

like image 647
Mithun Sreedharan Avatar asked Aug 19 '11 08:08

Mithun Sreedharan


1 Answers

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.

like image 80
JosephL Avatar answered Oct 09 '22 22:10

JosephL