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());
}
}
});
Related
I am wondering if it is possible to update the fields of a document from a collectionGroup query. I have set up my query as below and I want to .update() a single field in the document the query returns.
Query query = db.collectionGroup("orders").whereEqualTo("restaurantid",fAuth.getUid()).whereEqualTo(docId,getId());
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()){
Order order = queryDocumentSnapshots.getDocuments().get(0).toObject(Order.class);
//can i update the document here?
}else
{
Log.d("STATUS ERROR", "QUERY IS EMPTY");
}
}
});
To write to a document in Firestore you need a DocumentReference to it. Your queryDocumentSnapshots.getDocuments().get(0) gives you a DocumentSnapshot, which has a getReference method. So:
Query query = db.collectionGroup("orders").whereEqualTo("restaurantid",fAuth.getUid()).whereEqualTo(docId,getId());
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()){
DocumentSnapshot snapshot = queryDocumentSnapshots.getDocuments().get(0);
// Order order = snapshot.toObject(Order.class);
DocumentReference ref = snapshot.getReference();
ref.update("fieldName", "value");
} else {
Log.d("STATUS ERROR", "QUERY IS EMPTY");
}
}
});
You can update value of any document with its reference and update method.
DocumentReference washingtonRef = db.collection("cities").document("DC");
washingtonRef.update(key, value);
I already have a code that get the Data from Firestore Database, the data consist of Date,Invoice numb, item type, qty and price. What i want is when i show it to recyclerview, the data is sorted asscendingly based on the invoice number. anybody know how ? thanks
private void filterSearch() {
pbloading.setVisibility(View.VISIBLE);
String filter = filterDate.getText().toString();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("sales").whereEqualTo("date",filter).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
String invoice = document.getString("invoice");
String date = document.getString("date");
String type = document.getString("type");
Integer qty = document.getLong("qty").intValue();
Integer price = document.getLong("price").intValue();
sales = new Sales(invoice, date, type, qty, price);
salesList.add(sales);
}
adapter = new SalesAdapter(SalesHistoryActivity.this, salesList);
recyclerView.setAdapter(adapter);
pbloading.setVisibility(View.GONE);
} else {
pbloading.setVisibility(View.GONE);
Toast.makeText(SalesHistoryActivity.this, "Error", Toast.LENGTH_SHORT).show();
Log.w(Tag.ITEM, "error getting documents", task.getException());
}
}
});
}
Use Firebase's orderBy() method.
Creates and returns a new Query that's additionally sorted by the specified field, optionally in descending order instead of ascending.
add .orderBy("invoice", Query.Direction.ASCENDING) to your query.
db.collection("sales").whereEqualTo("date", filter).orderBy("invoice", Query.Direction.ASCENDING).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
//...
Try like the following.
for (QueryDocumentSnapshot document : task.getResult()) {
// ....
salesList.add(sales);
}
Collections.sort(salesList, new Comparator<Sales>(){
public int compare(Sales lhs, Sales rhs) {
return lhs.getInvoice().compareTo(rhs.getInvoice());
}
}
);
adapter = new SalesAdapter(SalesHistoryActivity.this, salesList);
Hope it helps you.
I faced a similar problem while retrieving Image URLS from firestore in a sorted order, So in order to achieve that I had use my own logic.
Step 1: I had to make sure that my keys were in order. The retrieval only orders them by value NOT the keys. Step 2: The following code is pretty self explanatory. It gets the keys and sorts them and then another loop adds the sorted key Item to another list that is sorted
FirebaseFirestore.getInstance().collection(collection).document(doc[0]).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.getResult() != null) {
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> desc = new ArrayList<>();
DocumentSnapshot doc = task.getResult();
Map<String, Object> map = doc.getData();
Object[] keysArray = map.keySet().toArray();
ArrayList<String> keysList = new ArrayList<>();
for(Object key : keysArray){
keysList.add((String)key);
}
Collections.sort(keysList);
for(String key : keysList){
urls.add(doc.getString(key));
desc.add(key);
}
viewPager2.setAdapter(setupViewPager(urls, desc));
styleViewPager();
}
}
});
I want to get auto generated id of a document
how can i getting these auto generated id's?
https://i.stack.imgur.com/tgui0.png
You can achieve this by using DataReference.push() method of DataReference object.
You can see here for more info.
you can try this :-
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("MartWayDB")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String id = document.getId();
//or you can store these id in array list
}
} else {
Toast.makeText(MainActivity.this, "Error getting documents."+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
or you can follow this link :
https://firebase.google.com/docs/firestore/quickstart?authuser=0
Hi I'm trying to get all the user's id present and store in an array list.
Here's my collection
here's my code:
` firebaseFirestore = FirebaseFirestore.getInstance();
Query firstQuery=firebaseFirestore.collection("Users");
firstQuery.addSnapshotListener(getActivity(),new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
lastVisible=documentSnapshots.getDocuments()
.get(documentSnapshots.size() -1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String blogPostId=doc.getDocument().getId();
ArrayList.add(doc.getDocument()); }
}
});`
I am fairly new to firebase.
Thank you
You should try to change the structure of your User Model, add a user_id field in your User model and match it so that it will be equal to the Uid generated by Firebase.Then make sure that when a User is created your document id will be equal to your user id
you can then retrieve it and store it in an ArrayList. I'll write the logic the rest should be easy for you to implement.
//implementing user model in registration
//getting the database reference
FirebaseFirestore mDb = FirebaseFirestore.getInstance();
Users user = new User();
user.setUser_id(FirebaseAuth.getInstance().getUid());
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.build();
mDb.setFirestoreSettings(settings);
// we make sure that the document id is equal to user id
DocumentReference newUserRef = mDb
.collection("Users")
.document(FirebaseAuth.getInstance().getUid());
newUserRef.set(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
Then in your activity :
ArrayList<Users> listUsers = new ArrayList<>();
//getting the database reference
FirebaseFirestore mDb = FirebaseFirestore.getInstance();
CollectionReference reference = mDb.collection(Users);
//Retrieving the data from the database
reference.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
//We specify that we want the id and add it to the arrayList
for (QueryDocumentSnapshot document : task.getResult()) {
Users users = document.toObject(Users.class);
listUSers.add(user.getId());
}
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;
}