A fluent API for ContentResolver#query

One thing that always felt ugly was using ContentResolver#query. A line like this isn't very readable and changing the query often introduce new bugs:

c =  getContentResolver().query(Contacts.CONTENT_URI, new String[]{Contacts._ID,Contacts.DISPLAY_NAME}, "("+Contacts.HAS_PHONE_NUMBER+"=? AND "+Contacts.STARRED+"=?) OR ("+Contacts.HAS_PHONE_NUMBER+"=? AND "+Contacts.STARRED+"<>?)", new String[]{"1","0","1","0"}, Contacts.DISPLAY_NAME);

So I thought it would be nice if you could write this query like this:

   c = Query.create().select(Contacts._ID,Contacts.DISPLAY_NAME).
   where( Query.create().
   where( Query.create().
   build().execute(getContentResolver(), Contacts.CONTENT_URI);

IMHO this is easier to read, easier to understand and easier to maintain. So I did a quick proof of concept and it turned out to be pretty easy.

No comments:

Post a Comment