2 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
最近出現(xiàn)了很多這樣的問(wèn)題。我不久前就找到了解決方案:使用任務(wù) 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
}
如果我犯了任何語(yǔ)法錯(cuò)誤,請(qǐng)?jiān)徫?,我?Java 有點(diǎn)生疏了。
確保您在主線程之外調(diào)用此代碼,否則它將崩潰。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以為此使用接口
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);
}
});
}
然后調(diào)用你的方法:
getNoteData(new NoteDataInterface() {
@Override
public void onCompleted(ArrayList<NoteFB> listNotes) {
Log.e("listNotes>>",listNotes.size()+"");
}
});
添加回答
舉報(bào)