搜索包含字符的字符串的数据库

时间:2015-07-01 12:28:08

标签: android sqlite

我使用以下代码搜索数据库中的确切字符串。例如,如果我想搜索“abc”,那么我需要输入“abc”。 我打算做的是在没有确切字符串的情况下启用搜索。例如,我可以输入“bc”并返回“abc”作为结果。我尝试将englishWord.equals("")更改为englishWord.contains("")。但是,这不起作用。

public List<Bean> getWords(String englishWord) {
        if(englishWord.equals(""))
            return new ArrayList<Bean>();

        String sql = "SELECT * FROM " + TABLE_NAME +
                " WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";

        SQLiteDatabase db = initializer.getReadableDatabase();

        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, new String[]{englishWord + "%"});

            List<Bean> wordList = new ArrayList<Bean>();
            while(cursor.moveToNext()) {
                int id = cursor.getInt(0);
                String english = cursor.getString(1);
                String bangla = cursor.getString(2);
                String status = cursor.getString(3);
                wordList.add(new Bean(id, english, bangla, status));
            }

            return wordList;
        } catch (SQLiteException exception) {
            exception.printStackTrace();
            return null;
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }

2 个答案:

答案 0 :(得分:1)

Relace

cursor = db.rawQuery(sql, new String[]{englishWord + "%"});

cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});

答案 1 :(得分:0)

试试这个。使用(&#34;%&#34; + englishWord +&#34;%&#34;)。代码是

 public List<Word> getWords(String englishWord) {

    String sql = "SELECT * FROM " + TABLE_NAME +
            " WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";



    SQLiteDatabase db = initializer.getReadableDatabase();

    Cursor cursor = null;
    try {
        cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});//Change here



        List<Word> wordList = new ArrayList<Word>();
        while(cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String english = cursor.getString(1);
            String bangla = cursor.getString(2);
            String status = cursor.getString(3);
            wordList.add(new Word(id, english, bangla, status));
        }

        return wordList;
    } catch (SQLiteException exception) {
        exception.printStackTrace();
        return null;
    } finally {
        if (cursor != null)
            cursor.close();
    }
}