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.
Related
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
}
});
I am facing a weird issue when trying to fetch the all documents under the collection.
Below is code to fetch the data from the firestore collection: "UserDetail"
db.enableNetwork();
db.collection("UserDetail")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
private static final String TAG = "UserDetail";
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful())
{
for (QueryDocumentSnapshot document : task.getResult())
{
String userEmail = document.getData().get("email").toString();
if (userEmail != null && !userEmail.equalsIgnoreCase(current_user_email))
{
<Performing some operation here.>
}
}
}
}
});
On new user registration, I am pushing User detail in this collection.
So here is what actually happening: when I register a user User1 on device1, then this code is returning the User1 in the result, but when I am trying to run the code from another device2 then User1 is not being fetched...
Can someone please help me here, not sure what is happening here.
UserDetail collection: this is how the data is getting stored under this collection. In screen shows there are 3 documents under UserDetail collection:
enter image description here
enter image description here
I have an Android App that has a recyclerView, where it shows the data returning from a query.
However, the query returns null when it should return something.
This is the query:
db.collection("Usuarios").whereEqualTo("email", mUser.getEmail()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
//There can only be 1 document due to previus code.
DocumentSnapshot document = task.getResult().getDocuments().get(0);
ArrayList<String> listasDelUsuario = (ArrayList<String>) document.get("idsListasDeCompra");
//Query to get all "Listas de compra" docs where its field "id" is in the Array "listasDelUsuario" (I checked with Log and this array contains the id of all the user's listOfID
db.collection("Listas de Compra").whereIn("id", listasDelUsuario).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult().isEmpty()) {
//It enters in this if, so the query is returning no data
}
}
}
});
}
}
});
Here is a screenshot with both collections so u can check the values im checking are the same.
Not sure why the query doesn't work, but in general I'd recommend accessing the list directly by its document ID, instead of querying for it:
db.collection("Listas de Compra").doc(listasDelUsuario).get()
I have created a application using Firestore in this app I want to save a same string in all documents of a collection in one click
For Example: See in the image. I have created a collection name Links. In this Collection I have created many Documents.
So I want to save string field: name and value:anyname, in all documents in one click on press button.
How it's possible? Please help.
To achieve this, please use the following code:
CollectionReference linksRef = rootRef.collection("Links");
linksRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Map<String, Object> map = new HashMap<>();
map.put("propertyName", "propertyValue");
placesRef.document(document.getId()).update(map);
}
}
}
});
All your documents will have now a new propertyName property that will hold the value of propertyValue.
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);