{"id":2006,"date":"2015-01-07T18:33:04","date_gmt":"2015-01-07T13:03:04","guid":{"rendered":"http:\/\/codetheory.in\/?p=2006"},"modified":"2015-01-31T00:26:43","modified_gmt":"2015-01-30T18:56:43","slug":"using-asyncqueryhandler-to-access-content-providers-asynchronously-in-android","status":"publish","type":"post","link":"https:\/\/codetheory.in\/using-asyncqueryhandler-to-access-content-providers-asynchronously-in-android\/","title":{"rendered":"Using AsyncQueryHandler to Access Content Providers Asynchronously in Android"},"content":{"rendered":"

In our previous posts we discussed SQLite access<\/a> and Content Providers<\/a>. Now access to a content provider will involve accessing some sort of persistent storage like a database or a file under the hood. Accessing a storage can be a long task and hence this should not be executed on the UI thread which will delay the rendering and could even lead to ANRs. Hence, background threads should be responsible for handling provider’s execution.<\/p>\n

<\/p>\n

Spawning new threads in the ContentProvider<\/code> itself is not a good idea especially in the case of query()<\/code> as you’ll then have to block and wait for the background thread to return the result (cursor) making it not asynchronous. Ideally execution must occur in a background thread and then the result communicated back to the UI thread. Now this could be implemented with Runnables, Threads and Handlers but Android provides us with a special class called AsyncQueryHandler<\/code><\/a> just for this purpose. This abstract class exposes an excellent interface to deal with the situation.<\/p>\n

Note: Ideally the background threads should be created by the application component that uses the provider by creating a ContentResolver<\/code><\/a> object. If the caller and provider are in the same application process, then the provider methods are invoked on the same thread as the ContentResolver<\/code><\/a> methods. However, if the processes are different then the provider implementation is invoked on binder threads (processes incoming IPCs).<\/p>\n

Using AsyncQueryHandler<\/h2>\n

AsyncQueryHandler<\/code><\/a> is basically an abstract class that wraps the ContentResolver<\/code><\/a> object and handles background execution of its operations (CRUD) as well as passing messages (result) from the between threads (background and main\/UI). It has four methods that wraps that of a ContentResolver<\/code>:<\/p>\n