Searching through ListView item and database on Android

。_饼干妹妹 提交于 2019-12-24 19:24:21

问题


I tried this code but it's too time-taking to iterate through all the list item. item_all is a list which contains data I got from the database.

et_Search.addTextChangedListener(new TextWatcher() {

    int textlength;
    long time = System.currentTimeMillis();

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        textlength = getSearchText().length();

        item_filtered = new ArrayList<StockItem>();
        long time = System.currentTimeMillis();

        int i = 0;

        do {
            int startpost = 0;
            int endpost = textlength;
            boolean found;
            do {
                found = false;
                if (getItemDesc(i).length() >= textlength 
                    && getSearchText().equalsIgnoreCase((String)getItemDesc(i).subSequence(startpost, endpost))) {
                    item_filtered.add(item_all.get(i));
                    found = true;
                }

                startpost++;
                endpost++;
            } while (endpost <= getItemDesc(i).length() && !found);

            i++;
        } while ((i < item_all.size()) && (item_filtered.size() <= 20));

        Log.v("Time", "Time needed " + (System.currentTimeMillis() - time));

        if (item_filtered.isEmpty())
            AppendList(new ArrayList<StockItem>());
        else
            AppendList(item_filtered);
    }

then I tried to use LIKE

try {
    String[] WHATYOUWANT = { "*" };
    String WHERECLAUSE = KEY_DESCRIPTION + " LIKE '%" + textIinput + "%' " ;
    String GROUPBY = null;
    String HAVING = null;
    String ORDERBY = KEY_ROWID + " ASC LIMIT 0,100 ";

    cursor = mDb.query(DATABASE_TABLE, WHATYOUWANT, WHERECLAUSE, null, GROUPBY, HAVING, ORDERBY);

    } catch (Exception e) {
        e.printStackTrace();
}

It works great except but it does not really do what I want.

What I want is the searched item match exactly with the input. Aay I input "abc", I don't want items which contain only "ab" or "bc" (not "abc") to appear.


回答1:


Try to use contains() instead of equalsIgnoreCase().

 if (getItemDesc(i).length() >= textlength
                            && getItemDesc(i)
                                    .contains(getSearchText()));

This might help you. :)



来源:https://stackoverflow.com/questions/11946010/searching-through-listview-item-and-database-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!