当数据库值发生变化时如何更新ListView?
目前我执行以下操作:
1)数据库链接到ListView:
String[] from = new String[]{DbAdapter.KEY_TITLE,
DbAdapter.KEY_DISPLAYED_VALUE,
DbAdapter.KEY_FAVORITE};
int[] to = new int[]{R.id.name, R.id.time, R.id.icon};
items = new SimpleCursorAdapter(this, R.layout.row, itemsCursor, from, to);
2)KEY_DISPLAYED_VALUE
在数据库中每2秒更改一次。然后调用items.notifyDataSetChanged()。但屏幕上的数据没有更新(R.id.time
目前是 TextView
,一旦此代码运行,将是 TextSwitcher
)。
使用 execSQL 更新数据库。
Currently I do the following:
1) database is linked to ListView:
String[] from = new String[]{DbAdapter.KEY_TITLE,
DbAdapter.KEY_DISPLAYED_VALUE,
DbAdapter.KEY_FAVORITE};
int[] to = new int[]{R.id.name, R.id.time, R.id.icon};
items = new SimpleCursorAdapter(this, R.layout.row, itemsCursor, from, to);
2) KEY_DISPLAYED_VALUE
is changed every 2 seconds in the database. Then items.notifyDataSetChanged()
is called. But data on the screen is not updated (R.id.time
is TextView
currently, will be TextSwitcher
once this code works).
Database is updated with execSQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为光标中的数据不会改变。在您的情况下,最简单的事情是每次更新数据库中的某些值时调用一个新查询并更改列表的光标(也许有一种通过广播或类似方式通知的方法)。另一种方法是通过查询在光标上注册一个通知 uri(请参阅 android 的记事本项目示例,了解如何创建内容提供程序,特别是插入方法。
但是,通过自动重新查询(记事本内容提供程序方式)的方式,您将收到通知对于每个查询,从而刷新每个项目的列表,并且您说数据库每 2 秒更新一次可能太频繁,并且您可能会阻止 ui 线程,从而使您的应用程序无响应,因此我建议管理您自己的刷新时间(我认为有些事情)。就像每 5 秒一次就可以了)。
希望这有帮助,编码愉快。
Well thats because the data in your cursor doesn't change. the simplest thing in your situation would be to call a new query and change the list's cursor every time you update some value in your database (maybe have a way of notifying via broadcasts or something like that). the other way is by registering a notification uri on the cursor with the query (see the notepad project example from android about making a content provider particularly the insert method.
however by going the way of autorequery (notepad content provider way) you will get notifications for each query and thus refreshing the list for each item and you saying that the database is updated every 2 seconds might be too frequent and you might block the ui thread making your app unresponsive. so i suggest managing your own refresh time (i think something like once every 5 seconds would work fine).
Hope this helps, happy coding.
以下解释了如何使用 notifyDataSetChanged() 以及您的示例不起作用的原因:
notifyDataSetChanged 示例
Here's an explanation of how to use notifyDataSetChanged(), and why your example isn't working:
notifyDataSetChanged example