how to search at firestore document's field - android

How to search at firestore documents? if firestore collection contains certain document and if there has a string field at document named 'title'. How can i search specific title using firebase android api.

It is documented in the Docs here, in the last section of the page, titled Get multiple documents from a collection.
Firestore provides a whereEqualTo function to query your data.
Example code (from Docs):
db.collection("cities")
.whereEqualTo("capital", true) // <-- This line
.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 documents: ", task.getException());
}
}
});

I have use MutableLiveData for search the specific user's name .where i pass the user's name and check whether it is available in Firestore or not
Here is my code:-
public MutableLiveData<UsersModel> getSpecificUser(final String name) {
final MutableLiveData<UsersModel> usersData = new MutableLiveData<>();
db.collection("users")
.whereEqualTo("name", name)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshot, #Nullable FirebaseFirestoreException e) {
if(e!=null || snapshot.size()==0){
Toast.makeText(activity, "User not found", Toast.LENGTH_SHORT).show();
}
for (DocumentChange userDoc : snapshot.getDocumentChanges()) {
UsersModel user = userDoc.getDocument().toObject(UsersModel.class);
if (user.name != null) {
if (userDoc.getType() == DocumentChange.Type.ADDED || userDoc.getType() == DocumentChange.Type.MODIFIED) {
usersData.setValue(user);
}
}
}
}
});
return usersData;
}

Related

How to retrieve the data that inserted in the map firebase fire store

I'm creating an app in the android studio IDE and I want to display the inserted data in a text box
but the problem is I don't know how to retrieve the data that I inserted in the driver field. The driver field is a map, Is there a way to retrieve the data insert in the driver field? This is my firebase fire store look like, I want to get the tricycle number data.
can anyone give me example on how to retrieve a data in a map collection field?
Following the documentation on getting data from Firestore, you can get a DataSnapshot object of the data at that location. Then using DocumentSnapshot#get() to get the value of an individual field.
This can be done using:
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference driverDocRef = db.collection("Driver Locations")
.document(driverId);
driverDocRef.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, "Driver #" + driverId + "'s Tricycle Number is " + document.get("driver.tricyclenumber", String.class));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
To make this into a function that you can reuse elsewhere, you can make use of Task#onSuccessTask() to chain tasks together.
One such implementation of this would be:
public Task<String> getDriverTricycleNumber(String driverId) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference driverDocRef = db.collection("Driver Locations")
.document(driverId);
return driverDocRef.get()
.onSuccessTask(new SuccessContinuation<DocumentSnapshot, String>() {
#NonNull
#Override
public Task<String> then(DocumentSnapshot document) {
if (!document.exists()) {
throw new DriverNotFoundException(); // <-- a custom exception of your choosing
}
return document.get("driver.tricyclenumber", String.class);
}
});
}
// to use:
getDriverTricycleNumber("someDriverId")
.addOnCompleteListener(new OnCompleteListener<Number>() {
#Override
public void onComplete(#NonNull Task<Number> task) {
if (task.isSuccessful()) {
String tricycleNumber = task.getResult();
Log.d(TAG, "Driver #" + driverId + "'s Tricycle Number is " + tricycleNumber);
} else {
Log.d(TAG, "Couldn't get tricycle number", task.getException());
}
}
});
Note: Optionally, you can simplify the above code using modern arrow notation and chaining:
public Task<String> getDriverTricycleNumber(String driverId) {
return FirebaseFirestore.getInstance()
.collection("Driver Locations")
.document(driverId)
.get()
.onSuccessTask(document -> {
if (!document.exists()) {
throw new DriverNotFoundException(); // <-- a custom exception of your choosing
}
return document.get("driver.tricyclenumber", String.class);
});
}
getDriverTricycleNumber("someDriverId")
.addOnSuccessListener(tricycleNumber -> {
Log.d(TAG, "Driver #" + driverId + "'s Tricycle Number is " + tricycleNumber);
})
.addOnFailureListener(exception -> {
Log.d(TAG, "Couldn't get tricycle number", exception);
});
If it's a map, then just use completely-standard dot notation:
const myFirstname = data.driver.firstname;
const myLastname = data.driver.lastname
etc etc etc

Android Firestore get field values by document id

I have a Firebase Firestore database in which I have to get all the field's inside a document by document id.
How to get the all the field values (inside Green Box) by document id (Red box)
If you want to get that specific document you can try this
DocumentReference docRef = db.collection("projects").document("YOURDOCIDHERE");
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());
}
}
});
If you want get all documents by key order then you can try making a query like this.
docRef.orderByKey()
Check firebase documention for more info.

How to fetch data just one time from firebase and don't listen to any data change

I'm new to firebase and recently started working on this. Every tutorial I saw, is about how to listen to data change in cloud firestore. What if I want to fetch teh data just once and don't wanna set anyy listener on them. Example scenario is, just fetching the data user last login time or profile data of any user
The documentation has a dedicated section about getting data a single time for a query. Just use the get() method on the query you build:
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());
}
}
});
Or, for a single document:
DocumentReference docRef = db.collection("cities").document("SF");
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());
}
}
});

Cloud Firestore Update

I'd like update document in cloud firestore according to value in document. Something like this. I have few documents with random names and values and one document with values id = 1 , name = patryk . And now I'd to update document with name=patryk. And I don't know document name because I make them like this and they have a random name.
b.collection("Users")
.add(postMapa)
.addOnCompleteListener
How to do this? here I need have the name of the document but I don't have.
Try this and make sure there will be only single document for name = patryk
db.collection("Users").whereEqualTo("name", "patryk").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e == null) {
String documentId = queryDocumentSnapshots.getDocuments().get(0).getId();
// here you have id but make sure you have only one document for name=patryk
}
}
});
Assuming that the id property is of type number and the name property is of type String, please use the following code in order to update all users with the id = 1 and name = patryk:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("Users").whereEqualTo("id", 1).whereEqualTo("name", "patryk");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
for (String id : list) {
rootRef.collection("Users").document(id).update("name", "New Name").addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Name Updated!");
}
});
}
}
}
});
If you are using a model class for your user, please see my answer from this post.
you can retrieve documents by their name (which does not really apply here):
DocumentReference docRef = db.collection("Users").document("patryk");
or you can query for values contained in a document (which might answer your question):
/* create a reference to the Users collection */
CollectionReference users = db.collection("Users");
/* create a query against the collection */
Query query = users.whereEqualTo("name", "patryk");
the rest is the same procedure, in both cases:
/* asynchronously retrieve the document */
ApiFuture<DocumentSnapshot> future = docRef.get();
/* future.get() blocks on response */
DocumentSnapshot document = future.get();
if (document.exists()) {
System.out.println("Document data: " + document.getData());
} else {
System.out.println("No such document!");
}
Simple way to get all document id under the collections:
firebase.collection("Users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
Log.d(TAG, list.toString());
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

Retrieve firestore reference

I am new to Android and Firestore, I was able to retrieve data from Firestore without any problems.
But, I'm not sure how to use the reference.
Here's the data structure for person;
{ name=abc, gender=male, title=software engineer, company=abc, useraccount=com.google.firebase.firestore.DocumentReference#4878aac
}
So I get the useraccount-reference like this;
DocumentReference userAccountRef = doc.getDocumentReference("useraccount");
My question is how to retrieve information from user account by using this userAccountRef? I don't see any API to get a document by reference.
To get a document from a DocumentReference you call get() on it. From the Firebase documentation:
userAccountRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null && 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());
}
}
});

Categories

Resources