【发布时间】:2019-06-10 10:25:09
【问题描述】:
所以,我正在使用 Firebase Cloud,并且在获得数据之前,我会查看三个参考资料。
这个问题让我创建了 3 个匿名嵌套类——它们看起来很糟糕,难以理解,并且可能难以维护代码。
我已经添加了该代码,希望得到您的建议 - 我应该如何清理它?
db.collection("users").document(mAuth.getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
提前致谢!
【问题讨论】:
-
为每个回调创建适当的方法
-
您能详细说明一下吗?给我看一小段代码,让我明白吗? @MiteshMachhoya
-
您还可以更改数据库架构/复制一些数据以进行单个数据库调用。
-
您应该学习如何使用异步方法返回的任务对象。您可以将他们的结果链接在一起。它在技术上比公认的答案更干净。这里有一个 4 部分的博客系列。 firebase.googleblog.com/2016/09/…
标签: android firebase google-cloud-firestore