使用 SimpleCursorAdapter 基于 sqlite 查询更新列表视图

Updating listview based on sqlite query with SimpleCursorAdapter



我有一个列表视图,其中包含一个个人资料图像视图、两个文本视图和一个最喜欢的图像视图。
在我在列表视图上方提供的搜索框中,我想查询 sqlite 数据库并使用 SimpleCursorAdapter 获取填充在我的列表视图中的更新结果。

以下是我的 create table 语句,其中显示了所有涉及的列。

public static String CREATE_TABLE_STMT="create table "
            +CONTACT_TABLE+" ("
            +ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            +NAME+" varchar(100) NOT NULL UNIQUE ,"
            +PHONE+" varchar(100) ,"
            +EMAIL+" varchar(100) ,"
            +JOBTITLE+" varchar(100) ,"
            +WEBPAGE+" varchar(100) ,"
            +PICTUREURL+" varchar(100) ,"
            +THUMBNAILURL+" varchar(100) ,"
            +PICTUREPATH+" varchar(100) ,"
            +THUMBNAILPATH+" varchar(100))";

我正在尝试 运行 以下查询来搜索 "NAME" 与我的搜索文本匹配的行。具体来说,我正在尝试检索名称列值以搜索查询开头的行。

String searchQuery = "SELECT ID as _id," + AppConstants.NAME+","+AppConstants.JOBTITLE+","+AppConstants.THUMBNAILURL +  " from " + AppConstants.CONTACT_TABLE + " where " + AppConstants.NAME + " LIKE '" + query + "';";


在 运行查询之后,我正在检查游标值并尝试更新我的列表视图

if (cursor != null) {
            Log.i(AppConstants.APPUILOG,"cursor not null");
            cursor.moveToFirst();
            String[] from = new String[] new String[] {NAME,JOBTITLE,THUMBNAILURL};
            int[] to = new int[] {R.id.textViewMain,R.id.textViewSub,R.id.contact_icon};
            SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.contact_list_item, cursor, from, to);
            mainListView.setAdapter(cursorAdapter);
        }else {
            Log.i(AppConstants.APPUILOG,"cursor is null");
        }

但是这段代码总是返回空白列表视图。

据我了解,您想在 ListView 中搜索。 我对吗 ?如果是,那么你需要改变你的方法,你不需要在 ListView 中搜索时与数据库交互。您需要在 ListView 中实现过滤器。您可以查看 this link 以获得完整的解决方案。