How to read a Firestore document? - java

I'm new to Android development ... ;-)
I need to know how to read a specific document I saved to Firestore, without having to copy the "documentPath" manually from the Cloud Firestore Console!
How do you do this automatically?
Next, I put some of the code where the documentPath is that I need to configure:
DocumentReference user = mFirestore.collection("Users").document(idUsers).collection("Companies").document(**"documentPath"**)
link to the image:
Company that I registered now and that I wish to need to show the user automatically
link to the document:
Document fields
I'm testing the following class:
private void ReadSingleEmpresa() {
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
String idUsuario = Base64Custom.codificarBase64(autenticacao.getCurrentUser().getEmail());
DocumentReference user = mFirestore.collection("Users").document(idUsuario).collection("Companies").document("gaSpr59pbeMmO9UpFxQQ");//document path
user.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d("ler doc", "DocumentSnapshot data: " + document.getData());
StringBuilder fields = new StringBuilder("");
//Some document fields
fields.append("Company name: ").append(document.get("nomeEmpresa"));
fields.append("\nEmail: ").append(document.get("emailRepresentante"));
fields.append("\nTelephone number: ").append(document.get("telefoneRepresentante"));
txtEmpresa.setText(fields.toString());
} else {
Log.d("ler doc", "No such document");
}
} else {
Log.d("ler doc", "get failed with ", task.getException());
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
This is the result:
Result of reading some document fields
It works but I do not know how to get the document I just registered among several. I only get it when I manually copy the document ID ...

Related

How to get data from a map field from Firebase Firestore?

I want to retrieve data stored as a map field on Cloud Firestore.
I want to get the 'Comment' as a string from 'All Comments' field to show it in a TextView.
How can I do it? (Java)
I tried this to add the data
Map<String,String> allComments=new HashMap<String,String>();
String commentContent=commentboxedittext.getText().toString();
allComments.put("Movie Name",name);
allComments.put("Comment",commentContent);
firebaseFirestore.collection("All Comments").document("MovieComments").set(allComments, SetOptions.merge());
And this to retrieve the data
DocumentReference docRef = firebaseFirestore.collection("All Comments").document("MovieComments");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> m=document.getData();
userComment=m.get("Comment").toString();
mName=m.get("Movie Name").toString();
} else {
Toast.makeText(MovieDetails.this, "No Such Document", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MovieDetails.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
But app crashes on doing this.
I also tried doing this to put the data and it worked but then I do not know how to retrieve data form this method.
Map<String,String> allComments=new HashMap<String,String>();
Map<String, Object> user=new HashMap<String,Object>();
userID=firebaseAuth.getCurrentUser().getUid();
userReference=firebaseFirestore.collection("Users ").document(userID);
String commentContent=commentboxedittext.getText().toString();
allComments.put("Movie Name",name);
allComments.put("Comment",commentContent);
user.put("All Comments",allComments);
userReference.set(user, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(MovieDetails.this, "Comment Added", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if(e instanceof FirebaseNetworkException)
Toast.makeText(MovieDetails.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
Toast.makeText(MovieDetails.this, "Values Not Stored", Toast.LENGTH_SHORT).show();
}
});
Assuming that "l4ir...Xy12" is ID of the authenticated user, to get the value of the "Comment" that exists within the "All Comments" map, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String comment = ((HashMap<String, Object>) document.getData().get("All Comments")).get("Comment").toString();
Log.d("TAG", comment);
} else {
Log.d("TAG", "No such document");
}
} else {
Log.d("TAG", "get failed with ", task.getException());
}
}
});
The result in the logcat will be:
sfgs
A few things to note:
DocumentSnapshot#get(String field) returns an object of type Object. Since each field inside a document represents a pair of keys and values, we can cast the result to an object of type HashMap<String, Object>.
Since we already have a Map, we can get the call Map#get(Object key) method, which returns the value associated with the key.

Getting Data from Firestore Never Completes Successfully

I'm new to NoSQL databases, but I'm attempting to use Firestore with an Android mobile application I'm developing.
I can write to the DB without any issues, but I can't read data. See code below:
DocumentReference docRef = db.collection("users").document("abc#gmail.com");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
User userFromDB = documentSnapshot.toObject(User.class);
}
});
When I was debugging, program execution didn't enter the 'onSuccess' function.
The code I'm using is based off the documentation (Get Data with Cloud Firestore - Custom Objects). I made sure that the 'User' fields in my code match the ones in the DB, and they all have 'get' methods.
Also, these are my rules:
match /{document=**} {
allow read, write: if true
}
I've been stuck on this for a while, any help would be highly appreciated.
The onSuccessListener is for write actions to the database. For getting data you need to use the onCompletedListener as shown in the official documentation:
DocumentReference docRef = db.collection("users").document("abc#gmail.com");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});

Firestore getting most liked posts

I'm making a simple app in which I want to introduce most liked posts. I'm using Cloud Firestore. My question is how the query should look like in this case? (I'm using Java)
Here's the Firestore tree:
-ROOT
--Posts
---Post
----Likes
Likes collection is set of users' ids.
Assuming that the Likes property is of type number and not String, please use the following code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference ref = rootRef.collection("Posts").document("Post");
ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
long numberOfLikes = document.getLong("Likes");
Log.d(TAG, String.valueOf(numberOfLikes));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
The output in your logcat will be the number of likes.

Firestore perform delete based on condition [duplicate]

This question already has answers here:
How to delete document from firestore using where clause
(12 answers)
Closed 9 months ago.
Is there a way I can perform a delete on Firestore documents where field1 =x and field2 = y?
I see the delete function but does not come with where.
If I use the transaction then there is get and delete but the get does not seem to accept "where" clause.
I hope I am missing something in the documentation.
Thanks
To achieve this, you need to create the desired query first and then just use the delete() method like this:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference itemsRef = rootRef.collection("yourCollection");
Query query = itemsRef.whereEqualTo("field1", "x").whereEqualTo("field2", "y");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
itemsRef.document(document.getId()).delete();
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Here's my method for both querying and deleting documents from firestore. First it queries the data, then it deletes it.
Note, this method must be adapted for integer/double values.
public void whereQueryDelete(final String collection, final String field, final String value) {
mFirestoreDatabase.collection(collection)
.whereEqualTo(field, value)
.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());
String idDelete = document.getId();
mFirestoreDatabase.collection(collection).document(idDelete)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}

Firestore - How Can I Get The Collections From a DocumentSnapshot?

Let's say I have a userSnapshot which I have got using get operation:
DocumentSnapshot userSnapshot=task.getResult().getData();
I know that I'm able to get a field from a documentSnapshot like this (for example):
String userName = userSnapshot.getString("name");
It just helps me with getting the values of the fields, but what if I want to get a collection under this userSnapshot? For example, its friends_list collection which contains documents of friends.
Is this possible?
Queries in Cloud Firestore are shallow. This means when you get() a document you do not download any of the data in subcollections.
If you want to get the data in the subcollections, you need to make a second request:
// Get the document
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
// ...
} else {
Log.d(TAG, "Error getting document.", task.getException());
}
}
});
// Get a subcollection
docRef.collection("friends_list").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting subcollection.", task.getException());
}
}
});

Categories