Reputation: 137
I'm using a ListView with a custom adapter to receive a JSON response and put it into a nice list - works great.
I'm now testing various exceptions and error handling and am catching errors received from my web API within the Android app. This all works great, handles well - but for the life of me I can't work out how to change the 'empty view' of a ListView once it has been set once.
It's within a fragment, if that makes any difference - but the ProgressBar and ListView are defined in an XML layout which is inflated in the Fragment. I have a TextView also inside there which contains some error text - I want to know how to switch the ProgressBar out for the TextView onError()!
Edit: Currently the ListView uses the ProgressBar as the empty view - I want to know how to later change this to another view - XML defined or programmatic.
The UI thread is not being locked as all API calls are carried out on an AsyncTask, so that's not the issue.
ListView.removeAllViews() caused a fairly imminent crash.
Apologies if this is trivial...
Upvotes: 3
Views: 1650
Reputation: 325
I have two empty views for my ListView. One is ProgressBar which I shows while I am loading data from database or server. Other is TextView, which I shows when I got error or have no data.
I put my ListView, ProgressBar and TextView in FrameLayout. And set visibility of both ProgressBar and TextView to Gone.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="@+id/my_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/empty_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
android:text="@string/no_contacts_found"/>
<ProgressBar
android:id="@+id/empty_progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center"
android:indeterminate="true"/>
</FrameLayout>
Before loading data from database or server, I change visibility of ProgressBar to Visible and set it as empty view of my ListView. So my ListView starts showing ProgressBar, indicating user that data is still loading.
If I got error or got no data from database or server, I set visibility of ProgressBar to Gone and change visibility of TextView to Visible. And then set TextView as empty view of my ListView.
Upvotes: 3
Reputation: 5108
You could define the empty view to be a FrameLayout and put whatever you want the empty state be inside that view and change it the way you'd change contents of any other view.
Upvotes: 4
Reputation: 39538
I just found this code in an old project, should work fine:
View emptyView = inflater.inflate(R.layout.id_of_your_layoout_file, parent, false);
getListView.setEmptyView(emptyView);
Upvotes: 0