【发布时间】:2020-05-28 09:25:39
【问题描述】:
目前遇到我从 firebase 获取数据的问题。我知道这是因为 Firebase 是异步的,所以当我进行 firebase 调用时,它会在自己的线程上执行,并且调用它的当前线程会继续执行。我正在使用来自 firebase 的数据填充对象列表,然后返回该对象列表。问题是,列表总是返回 null,因为 firebase 代码的执行没有及时完成。
我创建了一些从 SQLite db 中获取的异步代码,效果很好,但这种方法似乎不适用于 firebase(我相信这是因为 firebases API 是异步的)这是我从 firebase 返回对象列表的方法.
/** Method to get activity data from firebase.
* @param userInput the user query to select the data
* @return a list of activity models based on the query
* */
public List<ActivityModel> retrieveActivityData(String userInput) {
Log.d(TAG, "retrieveActivityData: starts");
List<ActivityModel> models = new ArrayList<ActivityModel>();
// execute the query in firebase
CollectionReference activfitCollection = db.collection("activity");
activfitCollection.orderBy("isoTimestamp")
.startAt(userInput)
.endAt(DateHelper.getDayEndingDate(userInput))
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: Getting data successful!");
// check to see if it exists
if (!task.getResult().isEmpty()) {
for (DocumentSnapshot documentSnapshot : task.getResult().getDocuments()) {
Log.d(TAG, "retrieveActivityData: document = " + documentSnapshot.getId());
// cast the document to the activity model
Log.d(TAG, "retrieveActivityData: document data " + documentSnapshot.getData());
ActivityModel model = mapToActivityModel(documentSnapshot);
models.add(model);
Log.d(TAG, "retrieveActivityData: array size" + models.size());
}
}
} else {
Log.e(TAG, "onComplete: Error getting documents: ", task.getException());
}
});
Log.d(TAG, "retrieveActivityData: array size outside " + models.size());
return models;
}
【问题讨论】:
标签: java android firebase google-cloud-firestore