嗨,我正在尝试获取所有用户ID并存储在数组列表中。
这是我的收藏
这是我的代码:
` firebaseFirestore = FirebaseFirestore.getInstance();
Query firstQuery=firebaseFirestore.collection("Users");
firstQuery.addSnapshotListener(getActivity(),new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
lastVisible=documentSnapshots.getDocuments()
.get(documentSnapshots.size() -1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String blogPostId=doc.getDocument().getId();
ArrayList.add(doc.getDocument()); }
}
});`
我刚接触Firebase。 谢谢
答案 0 :(得分:0)
您应该尝试更改用户模型的结构,在用户模型中添加一个user_id字段并进行匹配,以使其与Firebase生成的Uid相等。然后确保在创建用户时创建文档ID将等于您的用户ID 然后,您可以检索它并将其存储在ArrayList中。我会写出逻辑,其余的应该易于实现。
//implementing user model in registration
//getting the database reference
FirebaseFirestore mDb = FirebaseFirestore.getInstance();
Users user = new User();
user.setUser_id(FirebaseAuth.getInstance().getUid());
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.build();
mDb.setFirestoreSettings(settings);
// we make sure that the document id is equal to user id
DocumentReference newUserRef = mDb
.collection("Users")
.document(FirebaseAuth.getInstance().getUid());
newUserRef.set(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
然后在您的活动中:
ArrayList<Users> listUsers = new ArrayList<>();
//getting the database reference
FirebaseFirestore mDb = FirebaseFirestore.getInstance();
CollectionReference reference = mDb.collection(Users);
//Retrieving the data from the database
reference.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
//We specify that we want the id and add it to the arrayList
for (QueryDocumentSnapshot document : task.getResult()) {
Users users = document.toObject(Users.class);
listUSers.add(user.getId());
}