方法查询db以返回结果

时间:2013-04-05 21:35:05

标签: android sqlite

应用程序无法运行。这反复发生:

04-05 21:29:09.570: E/AndroidRuntime(1069): Caused by: java.lang.IllegalArgumentException: 
   Cannot bind argument at index 1 because the index is out of range.  
   The statement has 0 parameters.

主要 - 通话方法

Cursor wow = db.trying("Gold");
       text = (TextView) findViewById(R.id.textView13);
       String quantity = wow.getString(0); //
       text.setText(quantity);

DB Handler - 方法

public Cursor trying(String vg){
        String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor  cursor = db.rawQuery(q, new String[] {vg});

            if (cursor != null) {
                cursor.moveToFirst();
            }
            return cursor;
    }

1 个答案:

答案 0 :(得分:1)

问题是

 String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";

在您的查询中,您已经指定了where condition的参数。之后您再次将其传递给查询

Cursor  cursor = db.rawQuery(q, new String[] {vg});

这令人困惑。因此,请尝试更改您的查询

String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor  cursor = db.rawQuery(q, new String[] {vg});

或者你采取另一种方法

   String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
    Cursor  cursor = db.rawQuery(q, null);
   if(cursor != null && cursor.getCount()>0){
   cursor.moveToFirst();
   //do your action
   //Fetch your data

}
else {
 Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
    return;
}  

Refer