数据库查询总是返回true?

时间:2013-12-15 00:46:32

标签: java android mysql

我一直在尝试在 android 中创建一个数据库。数据库正在存储(我使用mySQL查看器来查看数据库)。但是当我尝试使用boolean检查特定条目时,它总是返回true。

MainActivity.java

  public void onClick(View view) {
        // TODO Auto-generated method stub
        switch(view.getId()){
        case R.id.save:
            db.addContact(new Contact(input.getText().toString(), "9100000000"));
            auth.setText("save");
            break;
        case R.id.check:
            auth.setText("check");          
            if(db.getContact(output.getText().toString())){
                auth.setText("Sucess");
            }
            else{
                auth.setText("Fail");
            }
            break;
        }
    }

DatabaseHandler.java

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

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

        return false;
    }

1 个答案:

答案 0 :(得分:2)

我会尝试进行一次更改...调用getCount()方法。

// I think you don't need this null check, but it shouldn't hurt anything.
if (cursor != null){
  // cursor.moveToFirst(); /* I don't think you need this either. */ 
  return (cursor.getCount() > 0);
}
return false;