android:使用ListAdapter和SimpleCursorAdapter刷新ListView
我正在尝试刷新使用创建为 SimpleCursorAdapter 的 ListAdapter 的 ListView 。
这是我在 onCreate 中创建 Cursor 和 ListAdapter 的代码,它们填充 ListView。
tCursor = db.getAllEntries();
ListAdapter adapter=new SimpleCursorAdapter(this,
R.layout.row, tCursor,
new String[] columns,
new int[] {R.id.rowid, R.id.date});
setListAdapter(adapter);
然后,我用另一种方法向数据库添加一些数据,但我不知道如何刷新 ListView。 stackoverflow和其他地方的类似问题提到了使用notifyDataSetChanged()和requery(),但ListAdapter或SimpleCursorAdapter的方法都没有提到。
I'm trying to refresh a ListView that uses a ListAdapter created as a SimpleCursorAdapter.
Here is my code for creating the Cursor and ListAdapter in onCreate which populates the ListView.
tCursor = db.getAllEntries();
ListAdapter adapter=new SimpleCursorAdapter(this,
R.layout.row, tCursor,
new String[] columns,
new int[] {R.id.rowid, R.id.date});
setListAdapter(adapter);
Then, I add some data to the db in another method, but I can't figure out how to refresh the ListView. Similar questions on stackoverflow and other places mention using notifyDataSetChanged() and requery(), but neither are methods of ListAdapter or SimpleCursorAdapter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可以通过创建一个新适配器并再次调用 setListAdapter 来刷新 ListView。
我在另一种方法中将其命名为adapter2。
我不确定为什么这是必要的,但它现在有效。如果有人有更好的解决方案,我愿意尝试。
I'm able to get the ListView to refresh by creating a new adapter and calling setListAdapter again.
I named it adapter2 in the other method.
I'm not sure why this is necessary, but it works for now. If anyone has a better solution, I'm willing to try it.
方法
notifyDataSetChanged
来自SimpleCursorAdapter
父类BaseAdapter
。父级实现了ListAdapter
,您应该能够将其传递给您的ListView
。尝试:
然后您应该能够使用
notifyDataSetChanged
。The method
notifyDataSetChanged
comes from theSimpleCursorAdapter
parent classBaseAdapter
. The parent implementsListAdapter
and you should be able to pass it to yourListView
.Try:
Then you should be able to use
notifyDataSetChanged
.在这种情况下,我建议通过扩展
BaseAdapter
类来使用自定义Adapter
。In that case I recommend to go with custom
Adapter
, by extending theBaseAdapter
class.如果需要从同一类中的其他方法访问适配器,则可以将适配器定义为类变量。然后你可以调用
changeCursor()
来刷新ListView。如果需要从另一个类中的方法更新列表视图,则应将适配器变量声明为
public static
You can define the adapter as a class variable if it needs to be accessed from other methods in the same class. Then you can call
changeCursor()
to refresh the ListView.If the list view needs to be updated from methods in another class, the adapter variable should be declared
public static
instead