I am learning Android, and my task is to retrieve steps data using Google Fit steps API. However, I keep getting "Task is not yet complete" error. I am not sure
This is my code for that part:
private List<Fitness> readHistoryDataFromGoogle() {
DataReadRequest readRequest = createDataReadRequest();
Task<DataReadResponse> response = com.google.android.gms.fitness.Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this)).readData(readRequest);
DataReadResponse responses = response.getResult();
List <Fitness> fitnessItems = parseFitness(responses);
return fitnessItems;
}
private List<Fitness> parseFitness(DataReadResponse dataReadResponse) {
List<com.example.mentalhealthapp.Fitness> fitnessItems = new ArrayList<>();
for (Bucket bucket : dataReadResponse.getBuckets()) {
for (DataSet set : bucket.getDataSets()) {
for (DataPoint dataPoint : set.getDataPoints()) {
int numSteps = dataPoint.getValue(Field.FIELD_STEPS).asInt();
long startDateTime = dataPoint.getStartTime(TimeUnit.MILLISECONDS);
long endDateTime = dataPoint.getEndTime(TimeUnit.MILLISECONDS);
fitnessItems.add(new com.example.mentalhealthapp.Fitness(numSteps, startDateTime, endDateTime));
}
}
}
return fitnessItems;
}
Thank you very much for your help!
You're getting this problem, because API requests (service calls) are Asynchronous
, they don't complete and return data immediately and you can't run them line by line like other code. you have to WAIT for that response to complete before you can access the data it returns.
from the documentation it tells you it's a REST api:
Brief look at documentation https://developers.google.com/android/reference/com/google/android/gms/fitness/RecordingClient suggests you should look at this for displaying data when it becomes available.