LA_
LA_

Reputation: 20419

How to update ListView in case when database value is changed?

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.

Upvotes: 3

Views: 8585

Answers (2)

Jayy
Jayy

Reputation: 14788

Here's an explanation of how to use notifyDataSetChanged(), and why your example isn't working:

notifyDataSetChanged example

Upvotes: 2

DArkO
DArkO

Reputation: 16110

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.

Upvotes: 3

Related Questions