Android: How do I make a ListView update itself periodically?

I never got this working in a straightforward manner. Sorry if I'm being a little vague. I'll try to elaborate on what I'm trying to do. I am trying to build a listview that grabs its data from a webservice. Once I initialize a listview, I want to keep polling the webserver periodically and update the contents of the listview. For this I am doing something like this:

public class SampleAutoUpdateList extends Activity {

     //Autoupdate handler
     private Handler handler = new Handler();
     private Runnable updater = new Runnable() {

     public void run() {

       /*
        * Update the list 
        */

       try {
          Log.i("UPDATE", "Handler called");
          searchAdapter = getFeed(URL);
          searchAdapter.notifyDataSetChanged();
          handler.postDelayed(this, Configuration.REFRESH_INTERVAL);
       } catch(Exception e) {
          Log.e("UPDATE ERROR", e.getMessage());
       }

      }

     };

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.linearmode);
      this.context = this;

      searchAdapter = getFeed(URL);
      LinearLayout l2 = (LinearLayout) findViewById(R.id.secondaryLayout);
      ListView list = new ListView(context);
      l2.addView(list);
      // display UI
      UpdateDisplay(list);
      updater.run();
     }

     private SearchAdapter getFeed(String URL) {
        try
        {
            SearchHandler handler = new SearchHandler();

            URL url = new URL(URL);

            String data = convertStreamToString(url.openStream());
            data = data.substring(data.indexOf('['), data.length()-1);
                    handler.parseJSON(data);

            return handler.getFeed();
        }
        catch (Exception ee)
        {
            // if we have a problem, simply return null
            Log.e("getFeed", ee.getMessage());
            return null;
        }
    }

    private void UpdateDisplay(View searchView) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        searchList = (ListView) searchView;

        myProgressDialog = ProgressDialog.show(this,       
                "Please wait...", "Loading search....", true); 

        new Thread() { 
            public void run() { 
                try{ 

                    Thread.sleep(2000); 
                } catch (Exception e) {  } 

                runOnUiThread(new Runnable() { 

                    @Override 
                    public void run() { 

                        if (searchAdapter == null)
                        {
                            Log.e("ERROR", "No Feed Available");
                            return;
                        }

                        searchAdapter.setContext(context);
                        searchList.setAdapter(searchAdapter);
                        searchList.setSelection(0);
                    } 
                }); 

                // Dismiss the Dialog 
                myProgressDialog.dismiss(); 
            } 
        }.start(); 
    }
}

And the SearchHandler class is simple:

public class SearchHandler  extends DefaultHandler {
    SearchAdapter _adapter;
    SearchItem _item;

    public SearchHandler()
    {
    }

    public SearchAdapter getFeed()
    {
        return _adapter;
    }

    public void parseJSON(String data) {
        // TODO Auto-generated method stub
        _adapter = new SearchAdapter();
        JSONArray parseArray;
        try {
            parseArray = new JSONArray(data);
                    for (int i=0; i < parseArray.length(); i++) {

                SearchItem item = new SearchItem();

                JSONObject jsonUser = parseArray.getJSONObject(i);
                item.set_from(jsonUser.getString ("from"));
                item.set_msg(jsonUser.getString("msg"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

No matter what I do, the handler gets called and the new items are fetched, but the list is never refreshed... Any ideas on what could be going wrong?


Asked by: Maya720 | Posted: 25-01-2022






Answer 1

Well, it is a little bit difficult to follow your code, since you only have a fragment of it, and few of the really relevant bits. For example, based on your available code, your list should be forever empty, since you never associate the searchAdapter with a ListView...at least in the code you have shown.

That being said, the following lines seem particularly odd:

        searchAdapter = getFeed(URL);
        searchAdapter.notifyDataSetChanged();

I am going to assume that getFeed() (not shown) creates a new ListAdapter of some sort. If getFeed() is creating a new ListAdapter, there is no need to call notifyDataSetChanged() on it, as its data set hasn't changed -- it's brand new. Moreover, unless you are associating this new ListAdapter to your ListView, the new ListAdapter will have no effect.

If I'm barking up the wrong tree, consider adding lines to your sample showing the implementation of getFeed() and where you are using searchAdapter.

Answered by: Kellan336 | Posted: 26-02-2022



Similar questions

Android: How to periodically send location to a server

I am running a Web service that allows users to record their trips (kind of like Google's MyTracks) as part of a larger app. The thing is that it is easy to pass data, including coords and other items, to the server when a user starts a trip or ends it. Being a newbie, I am not sure how to set up a background service that sends the location updates once every (pre-determined) period (min 3 minutes, max 1 hr) until the user...


Android: How to periodically send location to a server

I am running a Web service that allows users to record their trips (kind of like Google's MyTracks) as part of a larger app. The thing is that it is easy to pass data, including coords and other items, to the server when a user starts a trip or ends it. Being a newbie, I am not sure how to set up a background service that sends the location updates once every (pre-determined) period (min 3 minutes, max 1 hr) until the user...


How to periodically scan for bluetooth devices on android

Hi this may sound as a stupid question.But I was unable to find any answers for this, thus posting here. I am building an indoor application which continuously scans the bluetooth dongles located at different locations in a place like a mall or library.As I move in the mall with android phone in my hand I should be able to get the nearest dongle which I can connect to(Stupid Idea but I want to do something else wit...


performance - Periodically check if android GPS has new data

I have successfully been getting GPS data through the registerLocationListener() and onLocationChanged() methods. The only problem with this is that the speed reading of my app freezes if there is no more GPS data (e.g. when I go indoors, enter a tunnel, etc). The behavior I want for my app is that the user is somehow notified that the speed reading is probably not accurate due to a lack of fresh data (set speed to zero, b...


java - Periodically fetching data (polling) from the server in Android

I working on the app where I get the data from the server using rest call and add it to the view. I get all the initial data correctly. I use AsyncTask for doing it. Now I want to periodically (say 2 mins) fetch the new data from the server and add it to view.Periodically fetching data (polling) from the server in Android.


Android - periodically wake up from standby mode?

I have an app that needs to send a periodic heart beat to a server, but when the phone goes into standby mode the background heartbeat thread dies. Is there anyway to wake the phone from standby, send the heartbeat and then go back to sleep programmatically? I want to avoid using PARTIAL_WAKE_LOCK if possible. Thanks


java - Best way to periodically executing AsyncTasks in Android

I am getting data from the server using AsyncTask. I need to update the data periodically. Whats the best way to do it?


Android Handler Periodically

This I want I want to achieve: An activity starts with no ClickListener and has four textviews all with white background I want to change the color of textview 1 to blue. Wait for 2 seconds and then change it back to white and change the textview 2 to blue. wait for 2 seconds and then change it back to white... so on till i have turned textview 4 to blue and back to white. O...


java - Periodically Update a TextView in Android Application

I am using the MediaPlayer class to play an mp3 file in my application. How do I update a textview control every second with the current position in the mp3 file?


android - Problem in getting location updates periodically

I am using the Location Manager to get location updates. I used Location Manager's RequestLocationUpdates(provider,timeinmilliseconds,distanceinmeters,listener). When do i provide minimum delay of 30 seconds to get next location updates, i assume that it should rest for 30 seconds to request for new location updates.But what i observed,it is not happening. I tried specifying minimum distance too, still didn...


android - Best way to perform an action periodically [while an app is running] - Handler?

I'm trying to perform an action periodically. I want to create a new instance of a class after, say, ever 3 seconds. Would it be best to implement this by using a Handler or a Thread? Is there an easier, sort of dopey way I could try? I'm really not good at using threads - I want to learn, but it is more important that I get this to function before worrying about good programming practices. new Thread(...






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top