Search code examples
javaandroidsqlitecursorandroid-sqlite

How to search a String from multiple columns in an Sqlite database and returns the results in listview?


I'm trying to search a String from my database that contains mainly 3 columns (Questions, answers and comments), so the user can search for a word, and any instance of that word in any columns should appear in the search result. I used this code but it returns only the search from the first column only. have you any idea what's wrong with my code:

public Cursor search(String searchString) {

    String[] columns = new String[]{ KEY_QUESTION,KEY_ANSWER, KEY_COMMENT};
    String where =  KEY_QUESTION + " LIKE ? OR "+ KEY_ANSWER  + " LIKE ? ";
    searchString = "%" + searchString + "%";
    String[] whereArgs = new String[]{searchString};

    Cursor cursor = null;
    try {if (database == null) {
        database = openHelper.getReadableDatabase();
    }

        cursor = database.query(TABLE_FLASH, columns, where, whereArgs, null, null, null);
    } catch (Exception e) {
        Log.d(TAG, "SEARCH EXCEPTION! " + e); // Just log the exception
    }
    return cursor;
}

Solution

  • You are providing only one argument but your query has two, so second one will be null. Try this:

    String[] whereArgs = new String[]{searchString, searchString};