Android - 如何立即ListView快速过滤

时间:2014-06-10 04:18:04

标签: android listview dictionary android-cursoradapter

我有一个包含超过300,000个单词的词典数据库,使用cursoradapter填写ListView。当在ListView中过滤一个单词时,软件延迟,有没有办法立即过滤单词?

这是Main的代码

    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    db=new WordDbAdapter(this);
    db.openDatabase();

    Cursor cursor=db.getAllWord();
    adapter=new SimpleCursorAdapter(this, R.layout.listview_item, cursor,new            String[] {"word"},new int[] {R.id.title}, 0);


    lv=(ListView) findViewById(R.id.listView1);
    lv.setAdapter(adapter);
    filter=(EditText) findViewById(R.id.editText1);


    filter.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub
            adapter.getFilter().filter(cs.toString());

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }
    });

这是数据库的代码:

public Cursor getAllWord()
{
    Cursor cursor = null;
    try {


        String sql="select rowid _id,word from anh_viet";
         cursor=mdb.rawQuery(sql, null);


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
    }
    return cursor;

}
public Cursor filterWord(String key)
{
    Cursor cursor = null;
    try {


        String sql="select rowid _id,word from anh_viet where word like '"+key+"%'";
         cursor=mdb.rawQuery(sql, null);


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
    }
    return cursor;

}

1 个答案:

答案 0 :(得分:0)

永远不要写这样的查询:

String sql="select rowid _id,word from anh_viet where word like '"+key+"%'";

它不安全(您可以使用SQL注入)并且每次都需要db重新分析和优化查询。而是使用绑定变量作为键。这将允许它缓存搜索(加速搜索)并防止任何SQL注入的可能性。