Sunday, August 11, 2013

Kinvey - Simple Aggregates and Paging

I have been working with Kinvey as the backend for Critters 2.0 for about a month. I was having problems setting a filter on a paged query and getting a total count of results with it.

Getting the Data

The first part of getting the data was easy. The Kinvey documentation makes this a simple process. Note that I am using the blocking versions of the various methods available as I am making these calls from an AsyncTask:

   // Get the list
   AsyncLinkedData<PetEntity> pets = mKinveyClient.linkedData(
     "Pets", PetEntity.class);
   pets.setCache(new InMemoryLRUCache(), CachePolicy.CACHEFIRST);

   try {
    Get data = pets.getBlocking(q1, null, null, null, 0, false);
    mPetEntities = data.execute();
   } catch (IOException e) {
    Log.e(TAG, e.getMessage());
   }

Getting the Aggregate Row Count

The Kinvey documentation did not cover this very well; however, their excellent support was able to provide me with a solution (hint: access the undocumented "_result" field of the query result set). I know if I was staying sharp while debugging, I would have caught this myself:

 try {
     GenericJson[] ret = mKinveyClient
       .appData("Pets", PetEntity[].class)
       .countBlocking(fields, q1).execute();
     retval = Integer.valueOf((ret[0].get("_result"))
       .toString());
    } catch (IOException e) {
     Log.e(TAG, e.getMessage());
    }
   } else {
    retval = 0;
   }