Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

list - Searching through ListView item and database on Android

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

This might help you. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...