使用 SimpleCursorAdapter 更新 Android ListView [英] Android ListView update with SimpleCursorAdapter
问题描述
嘿,我使用列表视图来演示存储在数据库中的条目.我还有一个 EditText 元素和一个按钮,用于将 EditText 的内容添加到数据库中.要将视图绑定到数据库内容,我使用 SimpleCursorAdapter 和以下填充函数:
Hey i use a listview for demonstrate entries which are stored in a database. I also have a EditText element and a button which adds the content of the EditText into the Database. To bind the view to the database content i use the SimpleCursorAdapter and following populate function:
private void populate() {
cursor = dbAdapter.getAllItems();
startManagingCursor(cursor);
String[] from = new String[] { DBAdapter.KEY_TASK };
int[] to = new int[] { android.R.id.text1 };
// Now create an array adapter and set it to display using our row
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to);
list.setAdapter(cursorAdapter);
}
如果我添加了一个新条目,我想通过单击按钮刷新列表视图,但这仅适用于 populate 函数,而不适用于通用适配器函数 notifyDataSetChanged();
.我有错误还是刷新列表视图的正确方法?
If i added a new entry, by clicking on the button i want to refresh the listview but this only works with the populate function and not with the common adapter function notifyDataSetChanged();
. Do i have a bug or is this the right way to refresh a listview?
推荐答案
你见过 this,尝试了 swap cursor 方法,或者尝试简单地调用 setAdapter() 又来了?
Have you seen this, tried the swap cursor method, or tried just simply calling setAdapter() again?
我遇到了类似的问题,我无法更新我的列表,我所做的只是创建了一个 refreshListView() 方法.现在,您可以从 onCreate() 开始调用它,并且可以在用户向数据库添加内容的任何时候调用它.它所做的只是将列表视图重新绑定到光标.考虑到所有弃用方法 (requery()) 和 notifyDataSetChanged() 问题,我认为这是最简单的方法.
I had a similar issue where I could not get my list to update, and what I did was just create a refreshListView() method. Now you can call this initially from your onCreate(), AND anytime a user adds something to the DB. All it does is re-bind the listview to a cursor. With all the deprecating methods (requery()), and issues with notifyDataSetChanged(), I decided this was the easiest way.
这篇关于使用 SimpleCursorAdapter 更新 Android ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!