0

I'm searching for a word (variable) that occurs in multiple columns of a table. The search has to return the name of the columns in which the word in found.
I could use a foreach loop to go through each column seperately and know the presence of the word in that particular column when the returned cursor isn't null.
The problem is on how to use two different variables (one for column name and one for the word) in SQL query or rawQuery.

My code is as follows:

String[] columnsList = {"col1","col2","col3"};
String[] wordsList = {"fireman","camper","builder"};
for(String i : wordsList){
   for(String j : columnsList){
      Cursor wordQuery = myDatabaseHandle.rawQuery("Select * from myTableOne WHERE " + j + " = ?",new String[]{i});
      if(!(wordQuery==null)){
       Toast.makeText(this,j+"is success",Toast.LENGTH_SHORT).show();
      }
   }
}

But i'm unable to get the answer. I used a seperate string as:

String queryString = "Select * from myTableOne WHERE " + j ;

and in the query,

Cursor WordQuery = myDatabaseHandle.rawQuery(queryString+" = ?",new String[]{i});

But, it's just toasting the names of all columns.

1 Answer 1

2

Your error is here:

if(!(wordQuery==null)){

The cursor is never null.

It can contain 0 records, though.
You can check its length by using wordQuery.getCount()

Something like:

if((wordQuery.getCount() > 0)){
Sign up to request clarification or add additional context in comments.

5 Comments

Looks like perfect answer .
@IntelliJAmiya Thank you, dear!
Thank you. But I used query instead of rawQuery and it worked perfectly. I didn't know the cursor couldn't be null.That's a new thing learnt :) I'll change it now.
I used query instead of rawQuery It makes no difference.
If you found this answer useful, flag it as answered. So you can remove this post from the Unanswered Question Queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.