所以我是Android的小菜鳥,我正在編寫一個簡單的應用程序,使用Google Fit來存儲用戶健身會話和步數,然後檢索它們。如何在繼續(Android)之前等待結果回調完成的方法?
我有兩種方法,一種是從雲中獲取給定日期範圍內的所有會話,下一個方法遍歷這些方法並累計步數。
問題是,雖然我首先調用提取方法,但結果直到我添加了這些步驟後才返回,所以步數始終爲零。
這裏是我的代碼:
private ArrayList<> results;
@Override
public ArrayList<IndividualSession> readAllSessions(Date dateFrom, Date dateTo) {
/* I haven't included the following code in this question just to keep things clean, but here there was
- The initialisation of the results ArrayList
- Creating the calendar and date objects
- Building the session read request
*/
Fitness.SessionsApi.readSession(mGoogleApiClient, readRequest).setResultCallback(new ResultCallback<SessionReadResult>() {
@Override
public void onResult(SessionReadResult sessionReadResult) {
for (Session session : sessionReadResult.getSessions()) {
List<DataSet> dataSets = sessionReadResult.getDataSet(session);
for (DataSet dataSet : dataSets) {
for (DataPoint dataPoint : dataSet.getDataPoints()) {
// Create new IndividualSession object, add data to it then add it to arraylist
IndividualSession individualSessionObject = new IndividualSession();
individualSessionObject.setFromDate(new Date(session.getStartTime(TimeUnit.SECONDS)));
individualSessionObject.setToDate(new Date(session.getEndTime(TimeUnit.SECONDS)));
individualSessionObject.setStepCount(dataPoint.getValue(Field.FIELD_STEPS).asInt());
results.add(individualSessionObject);
}
}
}
Log.i(TAG, "Number of sessions found while reading: "+results.size());
}
});
return results;
}
@Override
public int getDaySteps(Date dateTo) {
int stepCount = 0; // to be returned
// Sort out the dates
Calendar calFrom = Calendar.getInstance();
calFrom.add(Calendar.HOUR, -24);
// Get the sessions for appropriate date range
ArrayList results = readAllSessions(calFrom.getTime(), dateTo);
Log.i(TAG, "Number of sessions found while trying to get total steps: "+results.size());
// Iterate through sessions to get count steps
Iterator<IndividualSession> it = results.iterator();
while(it.hasNext())
{
IndividualSession obj = it.next();
stepCount += obj.getStepCount();
}
return stepCount;
}
此輸出
"Number of sessions found while trying to get total steps: 0"
"Number of sessions found while reading: 8"
你在哪裏試圖「等待」?調用'readAllSessions'後? –
我試圖在內部等待public int getDaySteps(Date dateTo)'''我需要等待'''readAllSessions(calFrom.getTime(),dateTo);'''在繼續之前返回一個值 – Lissy
@VinceEmigh我認爲沒有必要明確地做到這一點。我瀏覽了文檔,API提供了一個機制來等待結果。 – CKing