Harts Harts - 24 days ago 6
Android Question

How to handle empty listView on fragment

How to show empty view, maybe with text saying no data.. if the String array is null

public class SermonsFragment extends ListFragment {
private String[] sermonsList = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//ListView for the sermon list
ListAdapter listAdapter = new ArrayAdapter<String>
(getActivity(), android.R.layout.simple_list_item_1, sermonsList);
setListAdapter(listAdapter);

//Some people use this but I can't use this syntax somehow
//SetEmptyView();


}


This is my xml file

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#222222" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<!-- Shows an image from your drawable resources -->
<ImageView
android:id="@+id/series_banner"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:src="@drawable/series_banner" />
<!-- Closing tag for the horizontal nested layout -->

<View
android:layout_width="fill_parent"
android:layout_height="10dp"
android:layout_marginBottom="10dp"
android:background="@android:color/darker_gray"/>

<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffffff" />

<TextView
android:id="@android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No Data" />

</LinearLayout>


</RelativeLayout>


I see some people use setEmptyView, but it does not work for me, I believe due to using ListAdapter.

Which bring me to another mini question, what's the different between ListView and ListAdapter, ArrayAdapter?. When to use which one.

Answer

The problem in my case actually because of I did not check

if(listAdapter.getCount() == 0)

which cause setListAdapter(listAdapter) error.

I dont have to do anything else, after that it will automaticly show

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No Data" />

without needed to do anything else.