2 回答

TA貢獻1776條經驗 獲得超12個贊
最近出現了很多這樣的問題。我不久前就找到了解決方案:使用任務 API。
public static ArrayList<NoteFB> getNotes() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
final String TAG = "FB Adapter";
final ArrayList<NoteFB> doFBs = new ArrayList<>();
try {
Task<QuerySnapshot> taskResult = Tasks.await(db.collection("notesItem").get(), 2, TimeUnit.SECONDS)
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
doFBs.add(document.toObject(NoteFB.class));
}
} catch(Exception e) {
Log.w(TAG, "Error getting documents.", e.localizedString());
}
return doFBs
}
如果我犯了任何語法錯誤,請原諒我,我的 Java 有點生疏了。
確保您在主線程之外調用此代碼,否則它將崩潰。

TA貢獻1829條經驗 獲得超13個贊
您可以為此使用接口
public interface NoteDataInterface {
void onCompleted(ArrayList<NoteFB> listNotes);
}
更改您的方法以使用接口:
public static void getNotes(NoteDataInterface noteDataInterface) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
final String TAG = "FB Adapter";
final ArrayList<NoteFB> doFBs = new ArrayList<>();
db.collection("notesItem")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
doFBs.add(document.toObject(NoteFB.class));
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
noteDataInterface.onCompleted(doFBs);
}
});
}
然后調用你的方法:
getNoteData(new NoteDataInterface() {
@Override
public void onCompleted(ArrayList<NoteFB> listNotes) {
Log.e("listNotes>>",listNotes.size()+"");
}
});
添加回答
舉報