如何在android中动态传递多个值?

时间:2012-09-03 06:18:54

标签: android

在我的项目中,我必须选择多个值并将其传递给查询。即page1包含复选框。我将选中的复选框id存储到数组中。 我正在改组那个数组并随机获取值。现在我需要将这些随机值传递给查询。在数据库中使用IN运算符我可以传递值 静态但我怎么能动态地将值传递给查询。

例如:(静态传递值)

SELECT * FROM Persons WHERE person_id IN ('21','22')

在上面的查询中,id 21和22之前已知道,因此我们静态传递但我想将值发送到动态查询。

Page1:
public static ArrayList<String> chksublist = new ArrayList<String>();

Page2:
 Collections.shuffle(chksublist );
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above line I want to send the random values which are in chksublist array.

4 个答案:

答案 0 :(得分:2)

String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ")";

但是在将chksublist发送到SQL查询之前对其进行洗牌对于从SQL获得的结果集没有影响。它不会随机置换您的结果。删除Collections.shuffle(chksublist);并使用

String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ") ORDER BY RANDOM()";

答案 1 :(得分:1)

了解如何动态传递值

  // Getting single contact
 public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
        KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
        new String[] { String.valueOf(id) }, null, null, null, null);

 // here   new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function
if (cursor != null)
    cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1), cursor.getString(2));
// return contact
return contact;
 }

答案 2 :(得分:1)

您可以像这样生成查询

int values[];      //it contains your generated values like 21,22....
String query="SELECT * FROM Persons WHERE person_id IN (";

for(int i=0;i<values.length;i++){
query=query+"'"+values[i]+"'";
if(i<values.length-1){
query=query+",";    //No , after last values
} 

}
query+=")";

最终传递此查询。

答案 3 :(得分:0)

试试吧

cursor = database.query(tablename,
                    new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null);

使用原始查询

String query = "SELECT * FROM Persons WHERE person_id IN ("+parameter1+","+parameter2+")";
db.rawQuery(query);