Reputation: 3765
I need to get all the documents inside a sub collection to get all the folders. My project structure is
Firebase Firestore root
|
|
Users collection (Collection)
|
|
Users' firebase UID (document)
|
|
Starred Messages (Collection)
|
|
Folder name(document)
|
|
Random Folder (To store the starred messages I made this collection)
|
|
Random Id (document)
|
|
All the values in it
Now I am adding folders like this
private void addFolder(String folderName){
HashMap<String, String> map = new HashMap<>();
map.put("sampleValue","sampleValue");
FirebaseFirestore.getInstance().collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID))
.collection(Constants.KEY_COLLECTION_STARRED_MESSAGE)
.document(folderName)
.collection(Constants.KEY_STARRED_MESSAGE_FOLDERS)
.document("sampleValueFolder2358")
.set(map)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) Log.d("folderCreation","done");
else Log.d("folderCreation","fail");
});
}
It works completely fine without error. But when I try getting those documents
private void getFolders(){
FirebaseFirestore.getInstance().collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID))
.collection(Constants.KEY_COLLECTION_STARRED_MESSAGE)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
Toast.makeText(this, "" + queryDocumentSnapshots.size(), Toast.LENGTH_SHORT).show();
for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()){
Folder folder = new Folder();
folder.name = documentChange.getDocument().getId();
folders.add(folder);
}
adapter.notifyDataSetChanged();
binding.refreshLayout.setRefreshing(false);
});
}
In the toast which I am trying to display, it shows 0 as the size? Why is this so? I verified it in the database too, but it exists ! See the image
Please help me in it.
Thanks in advance 🙂.
Upvotes: 1
Views: 117
Reputation: 598887
The documents in the "Starred Messages"
collection shown in italic in the console screenshot, which means that those documents don't actually exist in the database and the console merely shows the IDs so that it can show subcollections under it.
Since the hi
, "jgug
and ok
documents don't actually exist in your database, reading from the Starred Messages
collection won't return them.
The solution is to create those documents when you add data under them, even if you leave them completely empty. Typically I prefer creating them with some fields I end up needing later anyway, such as createdAt
with the timestamp of when the document is created.
Upvotes: 2