0

I am looking to refresh a ListView without reloading the page. More precisely I have a service that is sending data for a ListView in an Activity, however the Activity loads long before the Service can get the data. So I need to be able to load/reload the ListView after the Activity has already loaded.

HandlerExploit
  • 8,131
  • 4
  • 31
  • 50

3 Answers3

1

Call notifyDataSetChanged() on the ListView's Adapter whenever you want to refresh it.

HandlerExploit
  • 8,131
  • 4
  • 31
  • 50
Saad Farooq
  • 13,172
  • 10
  • 68
  • 94
1

I found that notifyDataSetChanged only works if you use the add, insert, remove, and clear functions on the Adapter, so I ended up doing it the following way in a similar implementation:

An AsyncTask fetches all the data in doInBackground. Then, when finished I set the list adapter for the first time in onPostExecute. To let the user know that something is loading, I just put a TextView on top of the Listview and set its text to "Loading.." in onPreExecute and then make it invisible in onPostExecute when the data is ready.

If you need to refresh the data, you just execute the AsyncTask again.

I like this way because you are only setting the ArrayAdapter once (i.e. when you finally have all the data). Here is more on AsyncTask in case you need it. The docs have some nice example code.

Community
  • 1
  • 1
koopaking3
  • 3,375
  • 2
  • 25
  • 36
1

I would say to use IntentService instead of Service. By, using IntentService you will be able to send data to the background Service and also receive the updated data while firing a BroadCastReceiver to update your UI. Here is a complete example how you can achieve your task using an IntentService.

HandlerExploit
  • 8,131
  • 4
  • 31
  • 50
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242