Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Content Provider for local SQLite DB: why?

I'm fairly new to Android development, but am having trouble wrapping my head around Content Providers and specifically what the benefits are (if any) to creating one for a single-app, single-DB SQLite data source. I can see that if I want to use a Sync Adapter, I need a Content Provider, but honestly the Sync API is so underwhelming that I don't think there is any advantage over rolling my own remote sync process using REST.

I also see that by implementing a Content Provider over my SQLite DB, I get a guaranteed Android-managed singleton, but I'm using AndroidAnnotations which can do singleton management for me and it doesn't seem from what I've read that it's even necessarily recommended to have a singleton DB helper as long as I manage my open connections properly.

Am I missing something? The Content Provider API seems surprisingly low-level and error-prone for a single DB app. Specifically managing URI mappings "by hand" and introducing that weird abstraction layer seems like it doesn't add much value.

So is there value in Content Providers for local SQLite DB's? And if so, is there some framework out there that will generate my URI mappings for me or is it strictly roll your own?

like image 414
jkraybill Avatar asked Mar 23 '23 03:03

jkraybill


1 Answers

First, the Sync API does much more than just loading data from your server. It controls batching your sync updates with other applications' syncs across the entire system, ensures connectivity before running, and optimizes for battery life across the entire system (as explained when running Sync Adapters periodically and in the transferring data using sync adapters guide).

Second, using a Content Provider allows you to very easily take advantage of the Loaders framework (available in the Support Library as well) and CursorLoader which allows your UI to automatically update as data changes in the Content Provider. This can vastly reduce the amount of boilerplate required throughout your Activities.

If the boilerplate of the Content Provider itself is an issue, then you can certainly use Annotation frameworks such as ProviGen to automatically generate the vast majority of a Content Provider for you.

There are also some features in Android that can only be done with the help of a Content Provider, including custom search suggestions and sharing app private files to other apps (although the helper FileProvider class that extends ContentProvider is most of what you'd need for that).

UI testing can be made much easier as well as you can use the provided MockContentProvider to mock up specific sets of data without having to change your Activity code (assuming it is only loading data from the Content Provider of course).

like image 56
ianhanniballake Avatar answered Apr 09 '23 16:04

ianhanniballake