简体   繁体   中英

Search sqlite android

Sorry for my english. I try create dynamicly serch. Example: we input serch word hellow , i input h -> he is serch all word who name start in latter he -> he is serch all word who name start in latter hel -> he is serch... and so on. The word may be upper and lower case like this HeLLow . My example

   public List<Map<String, String>> getSearch(String tableName, String search) {
        String query = "SELECT * FROM " + tableName + " WHERE `name` LIKE " + search;

        Cursor cursor = db.rawQuery(query, null);
        List<Map<String, String>> list = new ArrayList<>();
        String[] names = cursor.getColumnNames();

        if(cursor.moveToFirst()) {
            do{
                Map<String, String> map = new HashMap<String, String>();
                for (int i = 0; i < names.length; i++) {
                    map.put(names[i], cursor.getString(i));
                }
                list.add(map);

            } while (cursor.moveToNext());
        }

        return list;
    }

I try do like this:

String query = "SELECT * FROM " + tableName + " WHERE name = " + search;

String query = "SELECT * FROM " + tableName + " WHERE name MATCH " + search;

its not work too, i have always list = 0

When you build up the word on letter by letter basis, append it with the wildcard notation, ie % , for example, "he%", next letter "hel%"

Build up the search variable, for each iteration of letter added on or removed from, append it with the wildcard each time, like, 'Hel%', then combine the SQL like this

String query = "SELECT * FROM " + tableName + " WHERE name LIKE " + search;

The keyword is the SQL word LIKE which will get you the hit on the rows found that contains the word like Hel%.

Alternatively, consider using FTS (full text search) extension for SQLite. Querying with FTS works blazingly fast, provides results regardless of uppercase or lowercase and comes natively with SQLite for Android SDK.

You can find a working example below: https://github.com/dawidgdanski/Bakery

Hope this helps somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM