David Kim
David Kim

Reputation: 9

How can I select from two different columns for my search feature?

So I created a database with two columns, Name and Info. Now for my search feature if user types something similar to info or name I want it to show on the screen. As of right now it only does one or the other I can't make it to do both. So I know the issue lies in my select method in database. As of right now it is set to like this:

now if I put "Info Like? " it shows the search based on the Info column and if I change that to "Name Like?" it shows the search based on Name column.

   public List<myList> getNameandInfo(String text) {
     SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();


    //Column Name from database table
    String[] sqlSelect = {"Name", "Info"};
    String tableName = "Grocery"; // table name

    qb.setTables(tableName);

    //This line of code only shows result for Info column
 Cursor cursor = qb.query(db, sqlSelect, "Info LIKE ?", new String[]{"%" + 
 text + "%"}, null, null, null);
    List<Mylist> result = new ArrayList<>();
    if (cursor.moveToFirst()) {
        do {
            Mylist myList = new Mylist();

    myList.setName(cursor.getString(cursor.getColumnIndex("Name")));

    myList.setInfo(cursor.getString(cursor.getColumnIndex("Info")));

            result.add(myList);
        }
        while (cursor.moveToNext());
    }
    return result;
}

//tried this line of code but it crashes the app
   Cursor cursor = qb.query(db, sqlSelect, ("Name LIKE ?")+("Info LIKE ?"), new String[]{"%" + text + "%"}, null, null, null);

Upvotes: 0

Views: 45

Answers (2)

forpas
forpas

Reputation: 164099

Change the WHERE part from:

("Name LIKE ?")+("Info LIKE ?")

to:

"Name LIKE ? AND Info LIKE ?"

or maybe you need OR?
Also for the arguments you need 2 strings, not only 1:

"%" + text + "%"

so change to something like this:

new String[]{"%" + text1 + "%", "%" + text2 + "%"}

If you have only 1 value to check for both Name and Info:

 new String[]{"%" + text + "%", "%" + text + "%"}

Upvotes: 1

bksoares
bksoares

Reputation: 25

Maybe you can make use of OR in the query:

Cursor cursor = qb.query(db, sqlSelect, ("Name LIKE ? OR Info LIKE ?"), new String[]{"%" + text + "%"}, null, null, null);

Upvotes: 1

Related Questions