-2

My app needs to periodically fetch data from the web and update itself every 5 minutes. For the same, I was using Asynctask to fetch the content and process it in the background thread before sending it to the UI thread. Recently, I came to know about Asynctask Loaders and its benefits. However, I am not able to figure out how to periodically call the loader every 5 minutes to update the content.

(Please note earlier I was using Timer to call task.execute(). I need to finally update my listview if there is any new content.)

3 Answers3

1

I'd use a timer for updating you data every 5 minutes. Inside the timer create an async task. Fetch the data in doInBackground(). Update the UI in onPostExecute(). You can pass the data you fetched in doInBackground() to onPostExecute(). For more information check: https://developer.android.com/reference/android/os/AsyncTask.html

beeb
  • 1,615
  • 1
  • 12
  • 24
  • This is what I had been doing so far. However, I read that rotating screens would restart the activity and hence loaders are better than asynctasks. What do you think? Is there a way I can use loaders and do the same task of periodically updating the data? – Pranav Sodhani Dec 30 '16 at 00:51
  • Check this: http://stackoverflow.com/questions/7120813/asynctaskloader-vs-asynctask – beeb Dec 30 '16 at 02:10
1

If you want your code to be executed only when your app is running, in order to call periodically a task and do something in your UI thread after fetching your information, you can use a ScheduledExecutorService.

In your activity, declare :

private ScheduledExecutorService scheduleTaskExecutor;

scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

Future<?> future = scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // Fetch your data
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // Do the update in your UI 
            }
        });

    }
}, 0, 5, TimeUnit.MINUTES); 

Where scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

If you need to cancel your ScheduledExecutorService in onPause of your activity to reuse it afterward, use:

future.cancel(true);

If you want to remove the service, use:

scheduleTaskExecutor.shutdown();
AncaS
  • 110
  • 7
1

I figured it out finally.

While using loaders, we need to use restartLoader instead of initLoader if we need to periodically update the loader with new data. RestartLoader kills the previous loader and establishes a new one, while initLoader ignores the creation of a new loader if there already exists a loader with that id.