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()+"");
}
});
添加回答
举报