Android:SQLite - Querying an Array in SelectionArgs as well as other string values

前端 未结 1 1986
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 07:05

I had the following code for Content Resolver Query:

String selection = Columns.NAME + \"=? and \" + Columns.AVAILABILITY + \"=?\";
String[] selectionArgs = { na         


        
相关标签:
1条回答
  • 2021-01-23 07:09

    SQL has the IN operator for this:

    String selection = Columns.NAME + " IN (?,?,?) AND" +
                       Columns.Availability + " = ?";
    String[] selectionArgs = { name[0], name[1], name[2], true };
    ...
    

    If the array size is not predetermined, you have to construct the selection string and the selectionArgs array dynamically:

    String selection = Columns.NAME + " IN (" + makePlaceholders(names.length) + ")" +
                       " AND " + Columns.Availability + " = ?";
    String[] selectionArgs = new String[names.length + 1];
    for (int i = 0; i < names.length; i++)
        selectionArgs[i] = names[i];
    selectionArgs[names.length] = true;
    ...
    

    with the function makePlaceholders copied from this answer:

    String makePlaceholders(int len) {
        StringBuilder sb = new StringBuilder(len * 2 - 1);
        sb.append("?");
        for (int i = 1; i < len; i++)
            sb.append(",?");
        return sb.toString();
    }
    
    0 讨论(0)
提交回复
热议问题