November 11, 2012

Android Content Providers Generator

During the refactoring of my two years old app DroidAlone, I decided to try to access to the storage through a ContentProvider.

Even if the official documentation warns that there is no need to use content providers if your app does not want to export it's data against other apps, there are a bunch of advantages in using a content provider in your app.

The main and more obvious advantage is that you can use a Loader with your data. Using loaders relieve you from managing the cursor, forgetting open cursors here and there and most of all, makes a lot easier for your ui to react to changes in your model. Well, more than easier, you don't have to do anything.

However, I am not writing this post to describe how to interact with an android content provider, nor how to implement a content provider. There are a lot of content provider tutorials out there that probably can explain how them work better than I could possibly ever do (and in a better English).

I am writing this post because while writing the content provider, I got bored.
It's a lot of code, always the same, that cannot be avoided, and you don't have to add any value to it. The best thing you can do is not getting distracted and write it with no errors. And it's loong (ok, not that long).

Given the "boilerplateness" of this problem, I thought I could take off some dust from my old SqliteHelper builder script and maybe make it able to generate the content provider class for me. And that's what I did.

Android Content Provider Generator

I added a couple of options to it, and now it can generate automatically for you (no more cut/paste, no more forgotten columns) the content provider class AND a client class with a bunch of methods you can use to add / update / delete / query your data.
A sample of the generated code is already included in the beta of my app and it seems to work properly.

I won't write any instructions or examples here, they are already in the github repo.
All you need to know is that with a 10 rows text file that describes your data, you can generate the whole content provider.

As I wrote on G+, it's certainly not the most elegant piece of python I wrote, but it makes it's job.

If you liked this post (or my script), consider following me on twitter @fedepaol

comments powered by Disqus