tags:

views:

47

answers:

1

I have one activity. OnCreate the activity gets the source (html) of a web page to a string and presents the result (after parsing it a bit) in a textview.

I would like the activity to reload/refresh periodically to always present the latest information.

What is the best solution for this?

+1  A: 

First of all... separate the updating logic from your onCreate method. So, for instance, you can create an updateHTML().

Then, you can use a Timer in order to update the page periodically:

public class YourActivity extends Activity {

 private Timer autoUpdate;

 public void onCreate(Bundle b){
  super.onCreate(b);
  // whatever you have here
 }

 @Override
 public void onResume() {
  super.onResume();
  autoUpdate = new Timer();
  autoUpdate.schedule(new TimerTask() {
   @Override
   public void run() {
    runOnUiThread(new Runnable() {
     public void run() {
      updateHTML();
     }
    });
   }
  }, 0, 40000); // updates each 40 secs
 }

 private void updateHTML(){
  // your logic here
 }

 @Override
 public void onPause() {
  autoUpdate.cancel();
  super.onPause();
 }
}

Notice that I'm canceling the updating task on onPause, and that in this case the updateHTML method is executed each 40 secs (40000 milliseconds). Also, make sure you import these two classes: java.util.Timer and java.util.TimerTask.

Cristian
Perfect, thanks a lot.
Raffe
I have a follow-up question. I changed my app to have 2 tabs. Each tab starts its own activity. The first tab uses the activity described above. After i added the periodic update to that tab/activity there is a quite large delay when i try to switch to the other tab. Would it be better to solve this by using views in each tab? In that case how do i make so that only one of the tabs/views are updated periodically?
Raffe