Unable to .getKey() after .add() to Cloud Firestore - java

I am migrating from Firebase Realtime Database to Cloud Firestore. Previously, I would .push() under the Realtime Database, and I would get the key of the .push() as follows:
final String key = mBaseRef.child("ABC").push().getKey();
It does not appear this method is available under the new Cloud Firestore. I am trying as such:
mStoreBaseRef.collection("ABC").add(pollMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
String key = String.valueOf(mStoreBaseRef.collection("ABC").document().getId());
Log.v("KEY", key);
Toast.makeText(getApplicationContext(),key,Toast.LENGTH_LONG).show();
}
}
The log simply is not returning the key that was created.

A reference to the added document is returned as the result of the completion task. The document ID is available from it:
mStoreBaseRef.collection("ABC").add(pollMap)
.addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
DocumentReference docRef = task.getResult();
String key = docRef.getId();
Log.v("KEY", key);
Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
}
}
});

You can replace
final String key = mBaseRef.child("ABC").push().getKey();
with
DocumentReference key = db.collection("ABC").document();
This will return the auto-generated ID.
You can then reference it later as:
key.set(data);
Or you can get the Firebase push ID as:
key.getId();

You can first get the Id by this code
db = FirebaseFirestore.getInstance();
String documentId=db.collection("MyCollection").document().getId();
and when you want to to set value for this document
db.collection("MyCollection").document(documentId).set(myDataObject);

Related

Why my Firebase firestore data is not showing in android

I am working on an application where anyone can list their products. I am storing data in Firebase Firestore in nested collection Now I want to retrieve that data and show that on my home screen. Now the data is showing but the problem is that it is showing only when I am login in with that same number through that I list that data into Firebase but when I try to log in with another number the data doesn't show. I want that to show to everyone who logged in to the app. Basically My app is just like OLX where anyone can list anything which shows to everyone.
MY CODE TO RETRIEVE THE DATA
//CODE TO GET CURRENT ID OR USER
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
//CODE TO GET THE DATA FROM FIREBASE
DocumentReference uidRef = firebaseFirestore.collection("listing_details").document(uid);
CollectionReference roomDetailsRef = uidRef.collection("room_details");
String doc_id = roomDetailsRef.document().getId();
roomDetailsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document != null) {
RoomsDetails obj = document.toObject(RoomsDetails.class);
roomsDetails.add(obj);
}
}
roomsAdapter.notifyDataSetChanged();
} else {
Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
}
}
});
You have .document(uid) in your path where UID is User ID of user currently logged in. When you use another phone number, that's a different user.
If you want to fetch room_details documents from all listing_details documents then you can use Collection Group queries like this:
db.collectionGroup("room_details").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// ... iterate over all docs and render
}
});

How to get nested collection from Firebase Firestore on Android?

I am working on an application where I have saved my data in firebase Firestore in nested collection now when I am trying to get/retrieve the data from Firestore but not able to get it. please guide me where am I wrong??
CODE TO WRITE/ADD THE DATA IN FIRESTORE
DocumentReference uidRef = firebaseFirestore.collection("listing_details").document(uid);
uidRef.collection("room_details").add(user).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(getContext(), "data added", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "data adding failure", Toast.LENGTH_SHORT).show();
}
});
CODE FOR DATA RETRIEVING
db.collection("listing_details").document().collection("room_details").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list)
{
RoomsDetails obj = d.toObject(RoomsDetails.class);
roomsDetails.add(obj);
}
roomsAdapter.notifyDataSetChanged();
}
});
DATA RETRIEVING CODE (UPDATED)
roomDetailsRef.document(doc_id).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
//GUIDE ME HERE HOW CAN I ITERATE THROUGH IT SIR PLEASE
}
});
Each time you're calling .document() to create the following reference, without passing anything as an argument:
db.collection("listing_details").document().collection("room_details")
// 👆
It means that you're generating a brand new unique document ID. If you want to create a reference that points to a particular document, then you have to pass the particular document ID that already exists in the database to the document() method, and not generate a new one.
So your code should look like this:
//Code to add data to Firestore.
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef = db.collection("listing_details").document(uid);
CollectionReference roomDetailsRef = uidRef.collection("room_details");
String docId = roomDetailsRef.document().getId();
roomDetailsRef.document(docId).set(user).addOnSuccessListener(/*.../*);
// 👆
See, I have used DocumentReference#getId() to get the ID of the document, and DocumentReference#set(Object data) to actually add the document to Firestore.
//Code to read data from Firestore.
roomDetailsRef.document(docId).get().addOnSuccessListener(/*.../*);
// 👆
See, I have passed the document ID that was generated earlier, to the CollectionReference#document() method.
Edit:
If you want to get all documents that exist under the room_details collection, then please use the following lines of code:
roomDetailsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document != null) {
RoomsDetails obj = document.toObject(RoomsDetails.class);
roomsDetails.add(obj);
}
}
roomsAdapter.notifyDataSetChanged();
} else {
Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
}
}
});

Create a custom document id in firestore in android, instead of generating random one

How can I edit this code so I can create my own custom document id in Firestore?
users.add(new Accounts(fname, lname, uname, email, pass)).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(CreateAccount.this, "Data saved to FireStore", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, e.toString());
}
});
If you want to create a custom document id insead of the one that is generated when using CollectionReference's add() method which:
Adds a new document to this collection with the specified POJO as contents, assigning it a document ID automatically.
You should use DocumentReference's set() method:
Overwrites the document referred to by this DocumentRefere
If you want to get the document id that is generated or use a custom id in your reference, then please use following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
//String id = usersRef.collection("users").document().getId(); //Gets de generated id
String id = "yourCustomId";
Accounts accounts = new Accounts(fname, lname, uname, email, pass);
usersRef.document(id).set(accounts);

Getting an ArrayList from Firestore and the document name

I'm new on Google Firebase and I'm trying to learn something about it.
I'm doing an Android app where you can create a group of person and set the title of the group..then, in the "group page", you can see all your group in a listview.
The structure of my firestore db is something like this:
users --> email(document) ---> Group(collection) --> GroupName(Document) and the group name document contains the partecipants arrayList (partecipant 0 : Name1, partecipant1: name2 etc).
I would like to retrieve the document id(which is the group title) and the arrayList of partecipants, but I don't know of to use the for each in the code...
This is my code:
public void load_list_view(){
String email = getEmail();
final DocumentReference docRef = db.collection("users").document(email).collection("Group").document();
docRef.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
titleArray.add(documentSnapshot.getId());
titleString = documentSnapshot.getId();
partecipantsArray.add(documentSnapshot.getString("partecipant"));
num_partecipants = partecipantsArray.size();
numArray.add(num_partecipants);
trash = R.drawable.trash_icon;
firstChar = Character.toString(titleString.charAt(0));
firstCharArray.add(firstChar);
customAdapter = new GroupAdapter(GroupActivity.this, firstCharArray, titleArray, numArray, trash);
listView.setAdapter(customAdapter);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GroupActivity.this, e.getStackTrace().toString(), Toast.LENGTH_LONG).show();
}
});
}
with titleArray.add(documentSnapshot.getId()); it retrieve a random ID and I can't understand why.
I haven't found enough documentation on Internet about Arraylist and firestore.
First of all, to get all the documents in a collection you should write your code differently as shown in this documentation.
db.collection("cities")
.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());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Secondly, if you are retrieving an ArrayList you should use (ArrayList<String>) documentSnapshot.get("key") instead of documentSnapshot.getString("key").
Thirdly, you are getting random Id because with this line of code (mentioned below) firebase is generating a new document reference with a random id. Reference Link.
final DocumentReference docRef = db.collection("users").document(email).collection("Group").document();
For your help, I have tweaked your code and you can try this code and check if it's working or not.
public void load_list_view() {
String email = getEmail();
final DocumentReference docRef = firestore.collection("users").document(email);
docRef.collection("Group")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot document : queryDocumentSnapshots) {
//Extracting Group name from each document
titleString = document.getId();
titleArray.add(titleString);
//Extracting participants ArrayList from each document
partecipantsArray.add((ArrayList<String>) document.get("participant"));
numArray.add(num_partecipants);
firstChar = Character.toString(titleString.charAt(0));
firstCharArray.add(firstChar);
}
num_partecipants = partecipantsArray.size();
numArray.add(num_partecipants);
trash = R.drawable.trash_icon;
firstChar = Character.toString(titleString.charAt(0));
firstCharArray.add(firstChar);
customAdapter = new GroupAdapter(GroupActivity.this, firstCharArray, titleArray, numArray, trash);
listView.setAdapter(customAdapter);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//HANDLE EXCEPTION
}
});
}
For People doing in kotlin you can do the following things to get an arraylist from FireStore
First get the ArrayList as String
Remove the char at first and last Index
Split the String at each ','
Convert the list to an Array List
Here is the Code
ArrayList(doc.document.get("id_here").toString().subSequence(1, doc.document.get("id_here").toString().length - 1).split(","))
Also it may have extra spaces so don't forget to use the functions
trimStart() && trimEnd()

Cannot Access Key of Document in Firstore Node

I write to the Firestore after creating a user, as coded below:
userMap.put("email", user.getEmail());
userMap.put("display_name", user.getDisplayName());
userMap.put("user_id", user.getUid());
userMap.put("provider", user.getProviders());
mStoreBaseRef.collection(USERS).add(userMap);
When this user is written to the Firestore, a unique ID is generated for that User.
Later on, I want to write to the user node, however I do not have the unique key that was generated. I query the "Users" node based on a specific ID of a user so that I can write to that node, but I am unsure how to obtain the key for that specific user:
Query x = mStoreBaseRef.collection(USERS_LABEL).whereEqualTo("user_id", mPollCreatorID);
x.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (DocumentSnapshot d : task.getResult()){
User user = d.toObject(User.class);
Log.v("USER", user.getUser_id());
//I need to add the document here of the unique key
mStoreBaseRef.collection(USERS_LABEL).add(followersMap);
}
}
I am trying to obtain mAQGM9S.......from below
They ID of a document is available through DocumentSnapshot.getId(). So:
Query x = mStoreBaseRef.collection(USERS_LABEL).whereEqualTo("user_id", mPollCreatorID);
x.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (DocumentSnapshot d : task.getResult()){
Log.v("ID", d.getId());
User user = d.toObject(User.class);
Log.v("USER", user.getUser_id());
//I need to add the document here of the unique key
mStoreBaseRef.collection(USERS_LABEL).add(followersMap);
}
}
You are asking for the push id of that document. For that, you should use getId() method. Here is how you can do that :
Query x = mStoreBaseRef.collection(USERS_LABEL).whereEqualTo("user_id", mPollCreatorID);
x.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (DocumentSnapshot d : task.getResult()){
User user = d.toObject(User.class);
//Getting push id
String pushId = d.getId();
Log.v("USER", pushId);
//...
}
}
Try it and let us know if it's working or not.

Categories

Resources