开发者

How to implement where clause on Android Query method?

I'm trying to query a word, for this I'm using the db.query method. But I want to use a WHERE clause. I've done like this on my code, but I guess there is something wrong there with开发者_StackOverflow my WHERE clause.

public String select(String wrd) {
  String list = new String();
  Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like " + wrd + "", null, null, null, "id desc");
  if (cursor.moveToNext()) {
     do {
        list = cursor.getString(0); 
     } while (cursor.moveToNext());
  }
  if (cursor != null && !cursor.isClosed()) {
     cursor.close();
  }
  return list;

}

I'm calling this method in other class, parsing a String argument.

Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);                                    
        String body;                                        
        if(cursor.moveToFirst()){
            body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
            if(body == ""){
                Toast.makeText(getBaseContext(), "There is no words to save!", Toast.LENGTH_LONG).show();
            }
                else{
                    String words = this.dh.select("Testando");
                    StringTokenizer st = new StringTokenizer(body);
                    while(st.hasMoreTokens()){
                         if(words == st.nextToken())
                         Toast.makeText(getBaseContext(), "found! "+words+"", Toast.LENGTH_LONG).show();
                         this.dh.insert(st.nextToken());                             
                         Toast.makeText(getBaseContext(), "The set of words has been updated!", Toast.LENGTH_LONG).show();                                                                                                              
                    }                       
                    StringBuilder sb = new StringBuilder();
                    sb.append("Set of words:\n\n");
                    sb.append(words + " ");                    
                    txtView.setText(sb.toString());
                }
        }  


I believe the problem has to do with the double-quotes in the below code:

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like " + wrd + "", null, null, null, "id desc");

Try this

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like \"" + wrd + "\"", null, null, null, "id desc");

Or even better

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
        "word like ?",new String[] {wrd} , null, null, "id desc");

Edit:

Use single quote instead of double-quote in your WHERE clause. See here

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like \'" + wrd + "\'", null, null, null, "id desc");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜