Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search similar strings in SQLite [closed]

I want to search table "TABLE_TOURS" for similar words of "query" in cloumn "COLUMN_TITLE" and return a list "List". helps me plzz

public List<Tour> getWordMatches(String query, String[] columns) {
    String selection =  ToursDBOpenHelper.COLUMN_TITLE + " MATCH ?";
    String[] selectionArgs = new String[] {query+"*"};
    return query(selection, selectionArgs, columns);
}
public List<Tour> query(String selection, String[] selectionArgs, String[] columns) {
    Log.i(LOGTAG, "getwordsmatches result"+ selection +" "+ selectionArgs);
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(ToursDBOpenHelper.TABLE_TOURS);

    Cursor cursor = builder.query(dbhelper.getReadableDatabase(),
            columns, selection, selectionArgs, null, null, null);
    Log.i(LOGTAG, "cursor of db result "+ cursor);
    List<Tour> tours = cursorToList(cursor);
    Log.i(LOGTAG, "tours are "+ tours);
    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return tours;
}

and its cursorToList method:

private List<Tour> cursorToList(Cursor cursor) {
    List<Tour> tours = new ArrayList<Tour>();
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            Tour tour = new Tour();
            tour.setId(cursor.getLong(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_ID)));
            tour.setTitle(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_TITLE)));
            tour.setCate(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_CATE)));
            tour.setDetail(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_DETAIL)));
            tour.setDescription(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_DESC)));
            tour.setImage(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_IMAGE)));
            tours.add(tour);
        }
    }
    return tours;
}
like image 806
Zakiye Maarefi Avatar asked Jan 07 '14 18:01

Zakiye Maarefi


1 Answers

You can use the SQL LIKE statement for this. In SQL, the % character represents any string of 0 or more characters. So, for example, you could write

SELECT * FROM MY_TABLE WHERE COLUMN_NAME LIKE '%dog%'

This will match any string containing "dog", such as "dog", "dogs", "I like dogs", and "123dog321".

Your exact arguments will vary based on the structure of your table, but this is the gist of it.

like image 89
Nathan Walters Avatar answered Sep 17 '22 11:09

Nathan Walters