0

In my application i need to sync database with server, where tons of records (approx 300k). I am using paging concept to download data in my application using AsyncTask and Http connection in doInBackground(). I want to download pages concurrently and save into database. Is it a good approach to run AsynTask in loop like below or is there a better way to do this?

for (int i = 0 ;i <totalPage ; i++){
    updateRecords(i);
}

private void updateRecords(int page) {

    UpdateRecordsAsyncTask updateRecordsAsyncTask = new UpdateRecordsAsyncTask(this, mContext);
    updateRecordsAsyncTask.setAsyncErrorListener(this);
    updateRecordsAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Param);
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Suresh Sharma
  • 1,826
  • 22
  • 41
  • Yes, you can definitely call async task from for loop, but i have only doubt that do you have callback of your task which will let you know that all the pages are downloaded successfully and stored in the DB. Because it may happen that you have 100 pages and 100 async task will run and mean while you try to access the data which is still not downloaded, if you have solution to that then your approach works fine. – Silvans Solanki Mar 08 '16 at 06:07

2 Answers2

0

You can use Service instead of AsnycTask. Being handling huge data that needed to be downloaded/upload. AsyncTask is definitely intended to run operations in background, but not such long operations.
If you need to interact with Activity , you can create call backs from service to intimate the UI.
Go through the below links for the same
1) Stackoverflow link
2) Service Tutorial
3) Android Service Tutorial
4) Service with call backs

Community
  • 1
  • 1
Sreehari
  • 5,621
  • 2
  • 25
  • 59
0

Use IntentService for downloading data from background. More clarification please visit following url.

[1]: http://developer.android.com/reference/android/app/IntentService.html

malli
  • 642
  • 2
  • 12
  • 30