从sqlite数据库中搜索一个值并在listview中检索

时间:2013-07-29 13:08:29

标签: android sqlite listactivity custom-adapter

如何在sqlite database中查找确切数据并在listactivity中检索?我试过这样但我没有得到这个价值。

search = (EditText) findViewById(R.id.alertsearch);

search.addTextChangedListener(new TextWatcher(){

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            list2.clear();
            db =  openOrCreateDatabase(Contactsnew.DB_NAME, MODE_PRIVATE, null);
            Cursor cTitle=db.rawQuery(" SELECT * FROM "+ Contactsnew.TABLE02 + " WHERE " 
                    + Contactsnew.userid + " = " + GetSet.getUserId() + " AND " + Contactsnew.TITLE +
                     " LIKE ? " ,new String []{search.getText()+"%"});
            custAdapter.changeCursor(cTitle);

            while(cTitle.moveToNext()){
                list2.add(cTitle.getString(2));
                }
            cTitle.close();
        }

3 个答案:

答案 0 :(得分:4)

在sqliteconnecter中创建一个方法并从各自的类中调用该方法。现在在ur sqlite类中键入以下代码。

Cursor cusror;

cursor=db.rawQuery("SELECT * FROM "+ Contactsnew.TABLE02 + " WHERE " 
                + Contactsnew.userid + " = " + Contactsnew.userId + " AND " + Contactsnew.TITLE +
                 " LIKE  '"+search.getText()+"%'");

以字符串形式打印查询并检查您是否获得了正确的值,然后返回光标。

试试这个然后说!!

答案 1 :(得分:3)

将以下方法放在数据库类中:

public ArrayList<String> getlist(String search) {

        ArrayList<String> alTasklist = new ArrayList<String>();

        try {
            Cursor mCursor = db.query(true, Contactsnew.TABLE02,
                    new String[] { your field list }, SearchColumnname + "='" + search
                            + "'", null, null, null, null, null);

            if (mCursor != null) {
                mCursor.moveToFirst();
                for (int i = 0; i < mCursor.getCount(); i++) {
                    alTasklist.add(mCursor.getString(0));
                    mCursor.moveToNext();
                }
                mCursor.close();
                return alTasklist;
            }
            return alTasklist;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return alTasklist;
    }

现在在您的活动中获取此方法,然后初始化将arraylist返回到ListView ...

答案 2 :(得分:0)

尝试this way

Cursor cTitle=db.rawQuery("SELECT * FROM "+ Contactsnew.TABLE02 + " WHERE " 
                    + Contactsnew.userid + " = " + GetSet.getUserId() + " AND " + Contactsnew.TITLE +
                     " LIKE  '"+search.getText()+"%'");