我正在制作一个将监听Firestore集合中新文档的应用程序。我尝试查看Firestore文档,但不适用于我的特定问题。 这是我的代码,监听文件更新数据
FirebaseFirestore.getInstance().collection("users/" + companyID + "/trips").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot querySnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
if (!querySnapshot.isEmpty()){
for (QueryDocumentSnapshot qds : querySnapshot){
tripList.add(qds.getId());
}
showTripList();//update trip list view
}
}
});
将列表显示到ListView
public void showTripList() {
ListView tripListView = findViewById(R.id.tripList);
if (tripList.size() != 0) {
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, tripList);
tripListView.setAdapter(arrayAdapter);//show trip list on screen
} else {
TextView noTripTxt = findViewById(R.id.noTripTxt);
noTripTxt.setVisibility(View.VISIBLE);//show "no trip has been made yet" text to user
}
}
logcat在这两行显示NullPointerException
FirebaseFirestore.getInstance().collection("users/" + companyID + "/trips").addSnapshotListener(new EventListener<QuerySnapshot>()
tripList.add(qds.getId());
答案 0 :(得分:0)
您共享的代码似乎尝试监听特定trips
的{{1}}子集合。但是,构建通往该收藏集的路径的方法似乎令人怀疑:
companyId
总路径应为collection("users" + companyID + "trips")
,因此代码更可能是:
users/${companyID}/trips
没有collection("users/" + companyID + "/trips")
,您的代码正在侦听不存在的顶级集合/
。这样就可以解释为什么您没有得到任何结果。
请注意,通过使用更明确的API变体,您可以轻松避免此类字符串连接问题:
users${companyID}trips
虽然最后一个变体更长,但它消除了犯下简单的字符串连接错误的机会。
在固定了收集路径的情况下,您的代码将侦听子集合中的数据。因此它将匹配多个文档,并得到listening to multiple documents in a collection文档中所示的collection("users").doc(companyID).collection("trips")
。
答案 1 :(得分:0)
这是对我有用的代码
FirebaseFirestore.getInstance().collection("users/" + companyID + "/trips")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
tripList.clear();//clear the ArrayList, because this method get all the document id instead of
//the one that just created
for (QueryDocumentSnapshot doc : value) {
if (doc.getId() != null){
tripList.add(doc.getId());//store the document IDs to ArrayList
Log.d(TAG, "Retrieved data: " + doc.getId());
}
}
showTripList();//show trip name to listView
}
});