Search code examples
androidgoogle-fit

Google fit fetch last record


Is it possible to fetch only last record from Google Fit ? Not timerange, but just one entry from data set. I need to find time when that record is written.

Let's say I have to sync data from my app with Google Fit. I need to know when the last updated record is synced so I could find all values that are newer and not synced yet. I can save timestamp in local database, but I think that this is cleaner.

Thanks!


Solution

  • Use the setLimit(int limit) method on the DataReadRequest.Builder.

    like so:

    long monthInMillis = 2592000000; // It can be a year or more if you want.. Any way you are limiting the result to 1 DataPoint.
    long endTime = new Date().getTime(); // Now
    long startTime = endTime - monthInMillis;
    
    DataReadRequest.Builder builder = new DataReadRequest.Builder();
    builder.read(dataType);
    builder.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS);
    builder.setLimit(1); // This will get the latest record for the dataType
    DataReadRequest readRequest = builder.build(); 
    
    mHistoryClient.readData(readRequest)
    .addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
        @Override
        public void onSuccess(DataReadResponse dataReadResponse) {
    
            for (DataSet dataSet : dataReadResponse.getDataSets()) {
                for (DataPoint dataPoint : dataSet.getDataPoints()) {
                    if (dataPoint.getDataType().getName().equals(DataType.TYPE_LOCATION_SAMPLE.getName())) {
                        // Location DataPoint
                        long startTime = dataPoint.getStartTime(TimeUnit.MILLISECONDS);
                    }
    
                    if (dataPoint.getDataType().getName().equals(DataType.TYPE_ACTIVITY_SEGMENT.getName())) {
                        // Activity DataPoint
                        long endTime = dataPoint.getEndTime(TimeUnit.MILLISECONDS);
                    }
    
                    if (dataPoint.getDataType().getName().equals(DataType.TYPE_STEP_COUNT_DELTA.getName())) {
                        // Steps DataPoint
                    }
                }
            }
        }
    });
    

    public DataReadRequest.Builder setLimit (int limit)

    Limits results to the latest limit data points. This parameter is ignored for aggregated queries. By default there is no limit.

    Doc reference: https://developers.google.com/android/reference/com/google/android/gms/fitness/request/DataReadRequest.Builder.html#setLimit(int)