1

Having a bit of trouble dealing with empty ListView in android. Here's what I've got:

public class MainActivity extends ListActivity {
...
refreshList();
...}


public void refreshAlbumList(){
    albumList=control.listAlbums();

    if (albumList.length!=0){
        ArrayAdapter<String> ap = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,albumList);
        setListAdapter(ap);
    }else{      
        //deal with empty list somehow, currently results in error
    }
}

What I've tried is:

  this.getListView().setEmptyView(findViewById(android.R.id.empty));

And then inserting a TextView with id empty into main_activity.xml But the result was that took over the screen and I couldn't see the list.

Current xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >

<ListView
    android1:id="@id/android:list"
    android1:layout_width="match_parent"
    android1:layout_height="wrap_content"
    android1:layout_weight="1" >
</ListView>

</LinearLayout>
1
  • An easy way would be declaring another textview right under your listview, while controlling its visibility dynamically via codes. Commented May 4, 2013 at 2:53

1 Answer 1

2

The ListView calls ListAdapter#isEmpty method to determine if it should show/hide itself and the empty view. You will therefore always need to set an ListAdapter.

So the answer is to always create your ArrayAdapter and always set it to the ListView. In your activities onCreate call ListView#setEmptyView method. Alternatively, you can simply have a TextView with the android:id="@android:id/empty" attribute and the ListActivity will detect it and assign it using the above method.

Example: https://gist.github.com/slightfoot/5519281

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately it isn't working. One mistake I made when putting in my code - I'm actually doing this: this.getListView().setEmptyView(findViewById(android.R.id.empty)); And that's what doesn't work, even with the textview xml in there.
Did you make sure your Adapter is getting set as I suggested?
Zima, I have added an example gist to answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.