Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView Live Updating

I have a ListView in a ListActivity that's bound to some data. I have a content provider that's providing the data.

The ListActivity gets the data by querying a content resolver:

Uri uri = Uri.parse("content://my.provider.DocumentProvider/mystuff");
contentCursor = this.getContentResolver().query(uri, null, null, null, null);

So now the activity has the cursor. It creates an adapter and attaches it to the list:

ListAdapter adapter = new DocumentListCursorAdapter(this, R.layout.main_row_layout, contentCursor, new String[] { "titleColumn" }, new int[] { titleColumnIndex  });
setListAdapter(adapter);

This works fine; the list shows the data in the cursor.

But now the content provider has new data. I want the list to update to show the new data.

The examples I've seen involve a call to the adapter's notifyDataSetChanged, but it seems to me that this breaks the separation between the content provider and the list, which is consuming the content.

Does the content provider need to know what adapters are attached to the cursor so it can call their notifyDataSetChanged method? Or is there a better way that doesn't see these two things coupled this way.

like image 304
stevex Avatar asked Mar 09 '12 14:03

stevex


People also ask

How can you update a ListView dynamically?

This example demonstrates how do I dynamically update a ListView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

Is ListView deprecated android?

It's worth to mentioned that the ListView is a kind of deprecated because the RecyclerView was introduced with the API 21 (Android Lollipop).

How do I notify a list on android?

Scroll down and long-press the “Settings” widget, then place it on your home screen. You'll get a list of features that the Settings shortcut can access. Tap “Notification Log.” Tap the widget and scroll through your past notifications.


1 Answers

I found the answer here:

http://mylifewithandroid.blogspot.com/2008/03/observing-content.html

In a nutshell, the provider calls notifyChange to indicate that the content at the URI has changed:

getContext().getContentResolver().notifyChange(uri, null);

And the ListActivity calls setNotificationUri on the cursor to register that it's interested in receiving notification of changes:

contentCursor.setNotificationUri(getContentResolver(), uri);

(Thanks njzk2 for pointing me in the right direction).

like image 84
stevex Avatar answered Sep 24 '22 15:09

stevex