Display "No Item" message in ListView - android

I've created some composie UIs in my android apps and there are some ListView controls -among other controls- inside a view. Because of this, I have used "Activity" as my activity base class.
Now I need to display a simple message like "No Item" when the ListView that is bound to my adapter is empty. I know this is possible when using ListActivity but I'm not sure what's the best approach for this?

You can have an empty view without a ListActivity! The correct method is as follows
First add an 'empty view' to your layout XML below your list
...
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<TextView
android:id="#+id/empty"
android:text="Empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
/>
...
Next override the onContentChanged method of your activity and set the empty view of your list to your empty view:
#Override
public void onContentChanged() {
super.onContentChanged();
View empty = findViewById(R.id.empty);
ListView list = (ListView) findViewById(R.id.list);
list.setEmptyView(empty);
}
That's it! Android will take care of hiding/showing the list and empty view when you update the adapter.
The Magic
Deciding whether the empty view is shown or not is handled by the superclass of ListView, AdapterView. AdapterView registers a DataSetObserver on the set adapter so it is notified whenever the data is changed. This triggers a call to checkFocus in AdapterView which contains the following lines
if (mEmptyView != null) {
updateEmptyStatus((adapter == null) || adapter.isEmpty());
}
and sets the empty view visibility based on whether the adapter is empty or not.

You're looking for the empty view of a ListActivity:
ListActivity
If you're using ListView you can use the method setEmptyView():
setEmptyView

Just combine your ListView with TextView:
<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="#+id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent" />
<TextView
android:id="#+id/list_empty"
android:text="No Item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Then check the count of items an chanche visibility on ListView accordingly:
ListView lv = (ListView)findViewById(R.id.list);
lv.setVisibility((adapter.isEmpty())?View.GONE:View.VISIBLE);
If you are using Custom Adapter, you can do this in the overridden notifyDataSetChanged method.

You can use Toast Message for this..
Check the Count of the Adapter value by adapter.getCount()
if(Adapter.getCount()!=0){
List.setAdapter(Adapter);
}else{
Toast.makeText(YourActivityName.this, "No Items Available",Toast.LENGTH_SHORT).show();
}

For the layout code by Joseph, you need to edit the #+id/list and #+id/empty to #android:id/*, like:
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<TextView
android:id="#android:id/empty"
android:text="Empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
/>
This way, you even don't need to override the onContentChanged() function.

The easiest way to achieve this was using a ListFragment instead of a ListActivity. ListFragment has the following convenience method:
setEmptyText("My no items message...");
Besides, using a ListFragment class has other advantages. For example, the possibility to combine it with the new AppCompat library (which you cannot do with ListActivity because you have to extend from ActionBarActivity).

Related

Android use 2 listview linked together

I'm pretty new on android, i'm currently reading a lot of documentation to understand how to start. I've tried to search before asking here but i'm not able to find relevant information.
My problem is have 2 listview in the same acivity.
The Listview A with a list of category.
The Listview B with a details data (at startup the values showed are based on the category 1 of the listviewA)
When a click on a item of the listviewA the data of the listViewB change to reflect the new selection and show the new list of details data.
Can someone give me the right direction or a link to a tutorial that cover this topic ?
Sorry i'm not able to post any code at the moment.
I am not sure that the type of layout you are trying to make is user friendly. It would give the users far more richer UI experience if you change with an ExpandableListView. You can check out a tutorial here. Using this would give you the chances of engaging the user via an interaction.
Anyway, if you are sure to go with ListView then simply create a root LinearLayout and within this you take two ListViews. But taking the second one as a listview does not make sense. Rather, instead of making the second control a ListView, take a TextView to show the details.Provide the height of both layouts (ListView and TextView) according to your requirement.
Look at this tutorial
2 Listviews:
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:visibility="visible">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/listView2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:visibility="visible">
</ListView>
</LinearLayout>
</LinearLayout>
1 ListView 1 TextView:
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:visibility="visible">
</ListView>
</LinearLayout>
<TextView android:id="#+id/TextView1" android:text="details"/>
</LinearLayout>
UPDATE:
Please explain your problem a bit more. Because, in your scenario the data between the list views is connected with each other. Say, if ListView A is about Products so ListView B is about ProductDetails. So you need to declare a class variable say ProductID which is common entity between both data and set this variable setOnClickListener in ``getView()` of ListView A and fetch the data regarding this just after that and set the Adapter of ListView B with the results of this query (which may be to SQL db or RESTful server).
I have used this strategy before and it worked out well for me.
Use a linear layout to position the two list views, Populate the 'category' listview and set a list adaptor for it. On this listview I set an OnItemSelectedListener which when activated set ups the list-adaptor on the second 'detail' view.
Depending on your exact need you can either replace the detail listview's adapter or just change the content the adapter looks at and tell it to refresh.
Try this:
After get listview by id (list_A) set click listener
list_A.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//here you can get click position from parameter position
// and do somthing in Adapter_B and then call notifyDataSetChanged() for Adapter_B
Adapter_B.notifyDataSetChanged();
}
});

Listview BaseAdapter class getview is being called multiple times for same position

actually my problem is same as this guy's.But I don't know how to resolve it.Here's my listview xml file.
<?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"
android:background="#FFFFFF">
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="3"
android:background="#CCCCCC"
android:id="#+id/tabs">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#CCCCCC"
android:textSize="20sp"
android:textColor="#000000"
android:text="#string/NewTask"
android:id="#+id/tab1"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#CCCCCC"
android:layout_weight="1"
android:textSize="20sp"
android:textColor="#000000"
android:text="#string/Friends"
android:id="#+id/tab2"
/>
<Button
android:layout_width="fill_parent"
android:background="#CCCCCC"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_weight="1"
android:text="#string/AddPeople"
android:textSize="20sp"
android:id="#+id/tab3"
/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#000000"
android:layout_below="#+id/tabs"
/>
</RelativeLayout>
I am trying to call a function in my listactivity from the onpostExecute of my AsyncTask class.
Here's the function of my listactivity.
public void SetImage(Bitmap bmp,int index)
{
View v = this.ls.getChildAt(index);
ImageView img = (ImageView)v.findViewById(R.id.tasks_userimg);
img.setImageBitmap(bmp);
}
This bmp is the bitmap downloaded in the asynctask class and ls is the listview and the index is the index of the item in the listview.When the postexecute runs I call this function with the arguments to update the listview item image.
The problem is exactly same as I've mentioned in the link i.e when I scroll it gives me error.But he solved the problem by changing the layout width of listview but it is not working here.
Seems that like many others , you have some problems with this special view .
I highly recommend watching the lecture "the world of listView".
They talk about a lot of topics related to listView , including the topic of calling getView multiple times on the same view. In short , the reason why it occurs is because getView is also called for measuring the listView items . You can use (and should) use the convertView in order to avoid un-needed inflating and fetching of data .
About the question itself , you should not use findViewById on the listView items , since they are getting re-used . For example , a view that was set for the 0-th position may be set to the 7-th position in case the user has scrolled down .
if you wish to update a single item from the listView , you can use something like this:
// itemIndex is the index of the item to update
final View v=listView.getChildAt(itemIndex-listView.getFirstVisiblePosition());
//now you update your view according to what you wish .
//you must of course handle the cases that you can't get the view .
Of course , once you do it , you will also have to update your data behind the adapter , so that the next time the user scrolls to this item , it will have the bitmap shown to it.
What you should do depends on the asyncTask you've used .
I assume that you download multiple bitmaps while the listview fills its items . If that's the case , check out this sample , or use my suggestion : have an asyncTask for each viewHolder you have . For each time getView is called , cancel the old one and create a new one for the current item.
1) Define your custom adapter
2) Apply holder pattern
3) Use some image uploader (for example this)
Take a look simple example

Android: ListFragment: How to refresh list

I have a list view which is shown on a fragment. I have a button at the bottom of the screen in which when pressed, will call a webservice to reteive any additional data. If there is additional data, I need to add it to the list view. I have searched this forum and so many other web sites to try and find how to do it, but I have had no success. Any help is much appreciated.
I am now thinking do I need to add the fragment dyncamically instead of having it defined on the following XML layout.
I am using a ListFragment to inflate a list view on the screen.
I have a screen with two fragments on it. The XML for the screen is below: -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<fragment
android:name="atos.mobilereporting.com.ReportList"
android:layout_width="323dp"
android:layout_height="match_parent" />
<fragment
android:name="atos.mobilereporting.com.ReportDetail"
android:layout_width="958dp"
android:layout_height="match_parent" />
</LinearLayout>
<Button
android:id="#+id/getReports"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh Mobile Reports" />
</LinearLayout>
The code to inflate the view is below: -
public class ReportList extends ListFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get list of reports...
repList = ReportDefinitionFactory.buildReportList(3);
activity = getActivity();
ListAdapter la = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,
ReportDefinitionFactory.getReportDescriptions(repList));
setListAdapter(la);
}
}
This code shows a simple list view with 3 rows on it.
It is at this point I must stop as I do not know were to go from here. I have the code which will add an additional row to the array that is used to initially build the list view, but I do not know how I can invoke a refresh on the list view.
Thanks
Martin
You need to call la.notifyDataSetChanged() to force refresh of the list once the data has changed.
Use the ArrayAdapter notifyDataSetChanged() function.
This could be added in the ArrayAdapter, if that is the location where the data is updated. Otherwise, add it to the same area that calls la.add().

Custom Listview Adapter, adding a static footer, and understanding R.id.list

There is something I'm just not getting, and I'm looking for assistance in understanding what is happening here.
I have a custom list adapter (that just extends BaseAdapter) that I have successfully been using to generate and display a list. Now I want to add a static footer to the bottom of my list. After looking at a number of resources (specifically this one) I've come to realize that my reluctance of using XML has to come to an end, and set up the following xml layout in a file called devices_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout android:id="#+id/bottom_control_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<ToggleButton android:id="#+id/bottom_control_toggle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textOff="Filter Favourites OFF"
android:textOn="Filter Favourites ON"/>
</LinearLayout>
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_above="#id/bottom_control_bar">
</ListView>
<TextView android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_empty_list"
android:layout_above="#id/bottom_control_bar"/>
</RelativeLayout>
After some adjustments to the activity that holds the list, I ran the code. I see my footer, (and also the tab widget which is parent to everything), but the area where the list goes is empty.
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.devices_list);
db = new DbManager(this);
db.open();
AllCur = db.fetchAllDevices();
startManagingCursor(AllCur);
list = new DeviceListAdapter(this, AllCur); //make my custom list adapter
setListAdapter(list);
}
Is there some way to link up the ListView widget declared in my xml with my DeviceListAdapter? It's pretty clear to me now that I'm not entirely sure about how this is all working. Any help in clarification would be much appreciated.
You have both the ListView and the TextView set to android:layout_above="#id/bottom_control_bar", which means the TextView will overlap the ListView. And, you have said that your ListView height is 0dip, which will make for an extremely short list.
I would define the ListView as being above the TextView and anchored to the top of the screen (android:layout_alignParentTop="true").
Is there some way to link up the
ListView widget declared in my xml
with my DeviceListAdapter?
You already are, by calling setListAdapter().

Android: failed to setContentView when switching to ListActivity

[update] I got the error, which says "Your content must have a ListView whose id attribute is 'android.R.id.list'". Appearently nothing in my xml is ListView. But is that required?
This is an follow-up issue on my previous question
android: which view should I use for showing text and image?
I read the article about creating ListView for LinearLayout. However, my following code failed at the setContentView() function when I changed "extends Activity" to "extends ListActivity", any idea why?
private TextView mSelection;
//private ImageView mImages;
static final String[] keywords = new String[]{"China", "Japan", "USA", "Canada"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactLayout);
mSelection = (TextView)findViewById(R.id.ContactNames);
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.contactlayout, R.id.ContactNames,keywords);
setListAdapter(adapter);
}
My Layout is from this article: http://www.curious-creature.org/2009/02/22/android-layout-tricks-1/
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="6dip"
android:src="#drawable/icon" />
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/ContactNames"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="My Application" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:ellipsize="marquee"
android:text="Simple application that shows how to use RelativeLayout" />
</LinearLayout>
I think you misunderstood the other posts I showed you in the previous question. They were explaining how to use a custom layout for each row in your list, not how to define the entire layout file for the activity. You need something like this:
(main.xml)
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:id="#android:id/list">
</ListView>
Note the very important line android:id="#android:id/list". You must have that in your ListView as that's what tells Android where your list is. The cacheColorHint is useful if your background isn't black - see this post for more details about that.
With the above lines you can give your activity a list that will be recognised properly. Here's a basic example:
public class TestProject extends ListActivity {
final static String[] ITEMS = {"blah", "floop", "gnarlp", "stuff"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listrow, R.id.textview, ITEMS);
setListAdapter(adapter);
}
}
Then the listrow layout is just this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textview"/>
</LinearLayout>
This is a really simple layout. If you want to get something more complicated, changes are you'll have to use a BaseAdapter, as that gives you calls getView(...) before each row. In that you can use different layouts depending on the contents of each row. However, BaseAdapter looks scary when you first try it, so be warned! :)
Yes, if you are using a ListActivity, you need to have a ListView who's id is android.R.list in your layout file.
If you aren't using a ListView in your layout, and I don't see one in there, then switch to using a regular Activity.
Actually, your (custom) layout doesn't need a ListView when using a list activity. The easy way to solve this is just remove the setContentView() line altogether. In simple terms, when you do it, Android "assumes" the layout you're using to contain a single full-screen ListView, and provides it for you.
If you want a different (richer) interface for the Activity though, you must code the XML and use the informed ID for Android to know how to show the list implied by the activity being a ListActivity after all. Note that the layout for an item isn't the same as the list, and although I haven't tried that, I assume you can have a custom item layout without having an explicit ListView in the activity layout.

Categories

Resources