Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating a "No Data" View for ListViews

Author: Rachee Singh
Published? true -- FormatLanguage: W

Problem:

When the ListView has no items to show, the screen would just appear blank. In order to show an appropriate message on the screen, indicating the absence of data in the list.

Solution:

Use of 'No Data' View from the XML layout.

Discussion:

Often we require to use a ListView in an Android App. Prior to the input of data by the user, the List is empty. This in general would show a blank screen. In order to make the user feel better, we might want to display an appropriate message (or even an image) stating that the list is empty. For this purpose, the concept of No Data View can be used. This is a simple process involving addition of a few lines of code in the XML layout of the activity that contains the list view.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView
    android:id="@+id/textView1"
    android:text="@string/app_name"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
    
<ListView
    android:id="@id/android:list"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/textView1"/>

<TextView
    android:id="@id/android:empty"
    android:text="@string/list_is_empty"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_below = "@id/textView1"
    android:textSize="25sp"
    android:gravity="center_vertical|center_horizontal"/>

</RelativeLayout>


The important point is line 'android:id="@id/android:empty'. This line ensures that when the list is empty, the TextView with this ID will be displayed on the screen. In this text view the string 'List is Empty' is displayed.

Less important, but interesting and relevant, is the use of a <kbd>RelativeLayout</kbd> and the use of <kbd>android:layout_below</kbd> to make the huge empty text area appear directly below the tiny <kdb>TextView</kbd> at the top, when the list is empty (i.g., effectively making the ListView and the "empty message" TextView the same size; only one will be set visible at a time).

Download:

The source code for this project is in the Android Cookbook repository at http://github.com/IanDarwin/Android-Cookbook-Examples, in the subdirectory ListViewEmpty.
No records found.