How to search for string match in specific row of table in database in android
Solution 1:
What you are doing wrong is that you check if the Cursor
object returned by rawQuery()
is null
.rawQuery()
returns a Cursor
which may be empty (without any rows) but it can never be null
.
You can check if there any rows in the Cursor
by checking its moveToFirst()
method.
Also never use concatenation of the parameters of the sql statement. It is not safe.
Use placeholders ?
and the 2nd argument of rawQuery()
to pass the parameters.
So change to this:
public Cursor finddata(String name, int ida, int guess){
String sql = "SELECT NAME1 FROM Capital_Names " +
"WHERE ID = ? AND ? IN (NAME1, NAME2, NAME3, NAME4, NAME5)";
return db.rawQuery(sql, new String[] {ida, name});
}
It seems in your code that you don't use the argument guess
of finddata()
, so you can remove it.
Also are you sure that you want to return only the column NAME1
? You can replace it with "SELECT * FROM..."
to return all the columns.
Solution 2:
public Cursor finddata(String name,int ida, int guess){
String Query = "SELECT NAME1 FROM Capital_Names
WHERE ID = '" + ida + "'
AND
(
NAME1='" +name+ "' OR NAME2='" +name+ "' OR NAME3='" +name+ "' OR
NAME4='" +name+ "' OR NAME5='" +name+ "')"
;
return db.rawQuery(Query,null);
}
Try this on...