In some case if the list is empty, the screen will become nothing. If you want to prompt the user if the list is empty, @android:id/list and @android:id/empty can be used.
Create a new AndroidEmptyListActivity extends ListActivity.
package com.exercise.AndroidEmptyListActivity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class AndroidEmptyListActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SetupListView();
}
private void SetupListView()
{
String[] listItems = new String[] {
"Hello!",
"It's a Demo to use ListActivity,",
"with list/empty...",
"Is it Great?",
"computer-help-tips.blogspot.com"
};
/*
String[] listItems = new String[] {
};
*/
ArrayAdapter<String> listItemAdapter
= new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
listItems);
ListView lv = (ListView)this.findViewById(android.R.id.list);
lv.setAdapter(listItemAdapter);
}
}
Modify the main.xml to have a ListView with android:id="@android:id/list", and a TextView android:id="@android:id/empty".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List is Empty"/>
</LinearLayout>
If the List is not empty, the ListView will be shown, otherwise TextView will be shown.
Download the files.