Programmatically adding thousands of Android contacts in large numbers

Using the ContentResolver.applyBatch and ContentResolver.bulkInsert methods to add thousands of contacts in one go is very slow. Does Android have a different way to bulk download contacts that is significantly faster?

I have tried the following approaches so far:

Using applyBatch (~ 75 seconds per thousand contacts)

For each contact:

  • Create a new ContentValues ​​object to represent the raw contact
  • Create a new ContentProviderOperation to insert into the RawContacts table.
  • Add this operation to the list and store its index
  • Create ContentValues ​​objects for other contact fields such as names and phone numbers
  • Create a new ContentProviderOperation to insert each one into the data table with a back reference to the raw contact operation.
  • Add these operations to the list

Finally, use ContentResolver.applyBatch to apply all operations.

Using bulkInsert (~ 40 seconds per thousand contacts)

For each contact:

  • Create a new ContentValues ​​object to represent the raw contact
  • Create a new ContentProviderOperation to insert into the RawContacts table.
  • Add this operation to the list

Then use ContentResolver.applyBatch to apply all operations. This returns an array of ContentProviderResults.

Now for each contact:

  • Parse the original contact ID from the corresponding ContentProviderResult.
  • Build an array of ContentValues ​​objects for all data fields for a contact, each with a field for a raw contact id
  • Use ContentResolver.bulkInsert to insert them into data table

Questions

  • In the second approach, I first do applyBatch on the RawContacts table entries, then bulkInsert on the data table. This is because I cannot figure out a way to provide the original contact IDs for the data records otherwise. Is there something similar to backreferences for bulkInsert that would allow me to add RawContacts and Data records at the same time?
  • applyBatch and bulkInsert can only perform as many inserts in one batch before they claim the transaction is too large. Therefore, they should be applied every 500 contacts or so. Is there a way to change this limit?
  • Is there a completely different, faster way to add thousands of contacts at once?
+3


source to share


1 answer


the first method you showed is the correct way, and then faster than the second method , it is also more secure.

When you insert both values ​​into RawContacts

and Data

into the same batch operation, if something goes wrong, DB will roll back the previous changes in that batch so that you don't leave any info zombies in any table.



To speed up the process, try splitting the work between different threads.

If you have 1000 contacts, create one thread that will process the top 500 and another that will process the bottom 500 and run them simultaneously. You can apply this to more threads if needed.

0


source







All Articles