Display “No Item” message in ListView

You can have an empty view without a ListActivity! The correct method is as follows

First add an ’empty view’ to your layout XML below your list

...
<ListView 
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

<TextView
    android:id="@+id/empty"
    android:text="Empty"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    />
...

Next override the onContentChanged method of your activity and set the empty view of your list to your empty view:

@Override
public void onContentChanged() {
    super.onContentChanged();

    View empty = findViewById(R.id.empty);
    ListView list = (ListView) findViewById(R.id.list);
    list.setEmptyView(empty);
}

That’s it! Android will take care of hiding/showing the list and empty view when you update the adapter.

The Magic

Deciding whether the empty view is shown or not is handled by the superclass of ListView, AdapterView. AdapterView registers a DataSetObserver on the set adapter so it is notified whenever the data is changed. This triggers a call to checkFocus in AdapterView which contains the following lines

if (mEmptyView != null) {
    updateEmptyStatus((adapter == null) || adapter.isEmpty());
}

and sets the empty view visibility based on whether the adapter is empty or not.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)