Android – ListView => setEmptyView()

By -

Today I came across this setEmptyView() method of ListView. Many times it happens that we make a call on web service and we receive nothing in response at that time listview is displayed blank. At that time we should display messages like:

  1. No Records Found.
  2. No Data Found.
  3. No Items Found.

How do we handle such situation when there is nothing(empty) to display inside the Android – ListView?

By using setEmptyView() of ListView, we can set the view and can appear in the screen whenever the adapter is empty.

For example,

ListViewLayout.xml

<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/layoutTitlebar">

	<ListView
	  android:id="@+id/listViewFriends"
	  android:layout_height="match_parent"
	  android:layout_width="match_parent"
	  android:background="@color/friendBGColor"
	  android:cacheColorHint="#00000000">
	</ListView>

	<TextView
	  android:id="@+id/empty"
	  android:text="@string/strNoRecordsFound"
	  android:layout_width="fill_parent"
	  android:layout_height="fill_parent"
	  style="@android:style/TextAppearance.Large"
	  android:gravity="center">
	</TextView>
</LinearLayout>

And Now, write this code to define Empty view:

ListView listViewFriends = (ListView) findViewById(R.id.listViewFriends);
// set your adapter here
// set your click listener here
// or whatever else
listViewFriends.setEmptyView(findViewById(R.id.empty));

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

Loading Facebook Comments ...
Loading Disqus Comments ...