Search code examples
androidgoogle-fit

Google Fit History API readDailyTotal: non-static method in static context


I'm trying to request the daily total of steps using Google Fit. The readDailyTotal(GoogleApiClient client, DataType dataType) method should handle this, however, when using the example code, the method is invoke in a static context while it's a non-static method.

The code in the API documentation:

PendingResult<DailyTotalResult> result = HistoryApi.readDailyTotal(client, TYPE_STEP_COUNT_DELTA);
   DailyTotalResult totalResult = result.await(30, SECONDS);
   if (totalResult.getStatus().isSuccess()) {
     DataSet totalSet = totalResult.getTotal();
     long total = totalSet.isEmpty()
         ? 0
         : totalSet.getDataPoints().get(0).getValue(FIELD_STEPS).asInt();
   } else {
     // handle failure
   }

I know there is another way to read daily total steps but I would like to use this method for cleaner code.


Solution

  • You are explicitly awaiting for the result which could take longer. Moreover, if you call that from a UI thread it will crash (you are not allowed to await in the main thread)

    I suggest you to move to this approach

    PendingResult<DailyTotalResult> stepsResult = Fitness.HistoryApi
                        .readDailyTotal(client, DataType.TYPE_STEP_COUNT_DELTA);
    stepsResult.setResultCallback(new ResultCallback() {
      @Override
      public onResult(DailyTotalResult it) {
        if (it.getStatus().isSuccess()) {
          DataSet totalSet = it.getTotal();
          long total = totalSet.isEmpty()
             ? 0
             : totalSet.getDataPoints().get(0).getValue(FIELD_STEPS).asInt();
        }
      }
    });
    

    I have this same code, and it works ok.

    Also note that the readDailyTotal method is the only one which does not require explicit user permission to access the Fitness API.