Imaginemos un mundo libre

La paz interior comienza en el momento en el que decides no permitir, que ninguna persona o evento, tome el control de tus emociones.

Android Code Snippets: Adapter notifyDataSetChanged()

leave a comment »

A common error when working with adapters in Android, is not to notify your adapter when your data has changed.  If you don’t do that, you’ll receive and exception like this:

java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification.

Just call the notifyDataSetChanged() method after you modify your content.  But, maybe even if you notified your adapter, you receive an exception like this:

java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.

That means, you need to call notifyDataSetChanged() from the UI thread.  It’s better to create a method, so you can call it at anytime:

private void notifyAdapter()  {
    activity.runOnUiThread(new Runnable()  {
        public void run() {
            listView.setAdapter(null);
            if(adapter != null) {
                adapter.notifyDataSetChanged();
             }
        }
    });
}

I assume you have a listview and adapter objects created.

Enjoy

Written by Ronny Yabar

August 2, 2013 at 1:18 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: