2013-10-14

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(Contacts.HAS_PHONE_NUMBER).eq("1").
   and().where(Contacts.STARRED).eq("0")
   ).or().
   where( Query.create().
   where(Contacts.HAS_PHONE_NUMBER).eq("1").
   and().where(Contacts.STARRED).ne("0")
   ).
   orderBy(Contacts.DISPLAY_NAME).
   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