I need after inner foreach finish and add all data in list then send to interface
but when but this line " view.setOrders(orderList); " below " orderList.add(order); "
my code run okye but not that is not performance , I need best way to collection list then send to interface ..
public ListenerRegistration getOrders() {
view.showLoading();
ListenerRegistration listenerRegistration = refOrders.addSnapshotListener((queryDocumentSnapshots, e) -> {
view.hideLoading();
if (e != null) {
view.onErrorMessage(e.getMessage());
} else {
List<Order> orderList = new ArrayList<>();
for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {
Order order = snapshot.toObject(Order.class);
order.setOrderId(snapshot.getId());
refUsers.document(order.getPhone()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
User user = task.getResult().toObject(User.class);
order.setName(user.getName());
order.setAddress(user.getAddress());
orderList.add(order);
}
}
});
}
//Here Back List size = 0
view.setOrders(orderList);
}
});
return listenerRegistration;
}
Since get() method is asynchronous which means that the code after the CompletionListener will be executed first and then after the data is retrieved the listener will get executed.
Therefore to solve the issue add the following line view.setOrders(orderList); inside the CompletionListener
if (task.isSuccessful()) {
User user = task.getResult().toObject(User.class);
order.setName(user.getName());
order.setAddress(user.getAddress());
orderList.add(order);
view.setOrders(orderList);
When I create a user i have a List with the Urls of the images that that user needs.
Like
final List<String> picturesUrls = pictureUrl;
My user object is
import java.util.List;
public class User {
public List<String> picturesUrls;
public User() {
}
public User(List<String> picturesUrls) {
this.picturesUrls = picturesUrls;
}
}
It all work fine, but when I want to get those data from FireStore
db.collection("Users").whereEqualTo("email",user.getEmail())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(QueryDocumentSnapshot document: task.getResult()){
Object obj = document.get("picturesUrls");
actualUser = new User(
picturesUrls
);
}
}
}
});
but In the User model, picturesUrls is the type of List and what gives me from FireStore is an object. For now in that list it is only 1 string.
How can I convert that object to a List to create the new User Object and then loop into that List to get the last value ("actual profile picture")
Thank you in advance!
First you convert DocumentSnapshot to instance of User class. You would have to initialize getter in User class. Then you can use getter to get the url list.
So you code will be like this :
db.collection("Users").whereEqualTo("email",user.getEmail())
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(DocumentSnapshot ds : queryDocumentSnapshots) {
User user = ds.toObject(User.class);
List<String> urlList = user.getPicturesUrls();
}
}
});
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());
}
}
});
}
Consider a collection of users. Each document in the collection has name and email as fields.
{
"users": {
"uid1": {
"name": "Alex Saveau",
"email": "saveau.alexandre#gmail.com"
},
"uid2": { ... },
"uid3": { ... }
}
}
Consider now that with this working Cloud Firestore database structure I launch my first version of a mobile application. Then, at some point I realize I want to include another field such as last_login.
In the code, reading all the users documents from the Firestore DB using Java would be done as
FirebaseFirestore.getInstance().collection("users").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
mUsers.add(document.toObject(User.class));
}
}
}
});
where the class User contains now name, email and last_login.
Since the new User field (last_login) is not included in the old users stored in the DB, the application is crashing because the new User class is expecting a last_login field which is returned as null by the get() method.
What would be the best practice to include last_login in all the existing User documents of the DB without losing their data on a new version of the app? Should I run an snippet just once to do this task or are there any better approaches to the problem?
You fell into a gap of NOSQL databases: Document oriented databases do not guarantee structural integrity of the data (as RDBMS do)
The deal is:
in an RDBMS all stored data have the same structure at any given time (within the same instance or cluster). When changing the structure (ER-diagram) you have to migrate the data for all existing records which costs time and effort.
As a result, your application can be optimized for the current version of the data structure.
in a Document oriented database each record is an independent "Page" with its own independent structure. If you change the structure it only applies to new documents. So you don't need to migrate the existing data.
As a result, your application must be able to deal with all versions of the data structure you've ever used in your current database.
I don't know about firebase in detail but in general you never update a document in a NOSQL database. You only create a new version of the document. So even if you update all documents your application must be prepared to deal with the "old" data structure...
I wrote some routines to help automate this process back when I posted the question. I did not post them since these are a bit rudimentary and I was hoping for an elegant Firestore-based solution. Because such solution is not still available, here are the functions I wrote.
In short, we have functions for renaming a field, adding a field, or deleting a field. To rename a field, different functions are used depending on the data type. Maybe someone could generalise this better? The functions below are:
add_field: Adds a field in all documents of a collection.
delete_field: Deletes a field in all documents of a collection.
rename_*_field: Renames a field containing a certain data type (*) in all documents of a collection. Here I include examples for String, Integer, and Date.
Add field:
public void add_field (final String key, final Object value, final String collection_ref) {
FirebaseFirestore.getInstance().collection(collection_ref).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
WriteBatch batch = db.batch();
for (DocumentSnapshot document : task.getResult()) {
DocumentReference docRef = document.getReference();
Map<String, Object> new_map = new HashMap<>();
new_map.put(key, value);
batch.update(docRef, new_map);
}
batch.commit();
} else {
// ... "Error adding field -> " + task.getException()
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// ... "Failure getting documents -> " + e
}
});
}
Delete field:
public void delete_field (final String key, final String collection_ref) {
FirebaseFirestore.getInstance().collection(collection_ref).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
WriteBatch batch = db.batch();
for (DocumentSnapshot document : task.getResult()) {
DocumentReference docRef = document.getReference();
Map<String, Object> delete_field = new HashMap<>();
delete_field.put(key, FieldValue.delete());
batch.update(docRef, delete_field);
}
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
} else {
// ... "Error updating field -> " + task.getException()
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// ... "Failure getting notices -> " + e
}
});
}
Rename field:
public void rename_string_field (final String old_key, final String new_key, final String collection_ref) {
FirebaseFirestore.getInstance().collection(collection_ref).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
WriteBatch batch = db.batch();
for (DocumentSnapshot document : task.getResult()) {
DocumentReference docRef = document.getReference();
String old_value = document.getString(old_key);
if (old_value != null) {
Map<String, Object> new_map = new HashMap<>();
new_map.put(new_key, old_value);
Map<String, Object> delete_old = new HashMap<>();
delete_old.put(old_key, FieldValue.delete());
batch.update(docRef, new_map);
batch.update(docRef, delete_old);
}
}
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
} else {
// ... "Error updating field -> " + task.getException()
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// ... "Failure getting notices ->" + e
}
});
}
public void rename_integer_field (final String old_key, final String new_key, final String collection_ref) {
FirebaseFirestore.getInstance().collection(collection_ref).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
WriteBatch batch = db.batch();
for (DocumentSnapshot document : task.getResult()) {
DocumentReference docRef = document.getReference();
int old_value = document.getDouble(old_key).intValue();
Integer ov = old_value;
if (ov != null) {
Map<String, Object> new_map = new HashMap<>();
new_map.put(new_key, old_value);
Map<String, Object> delete_old = new HashMap<>();
delete_old.put(old_key, FieldValue.delete());
batch.update(docRef, new_map);
batch.update(docRef, delete_old);
}
}
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
} else {
// ... "Error updating field -> " + task.getException()
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// ... "Failure getting notices -> " + e
}
});
}
public void rename_date_field (final String old_key, final String new_key, final String collection_ref) {
FirebaseFirestore.getInstance().collection(collection_ref).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
WriteBatch batch = db.batch();
for (DocumentSnapshot document : task.getResult()) {
DocumentReference docRef = document.getReference();
Date old_value = document.getDate(old_key);
if (old_value != null) {
Map<String, Object> new_map = new HashMap<>();
new_map.put(new_key, old_value);
Map<String, Object> delete_old = new HashMap<>();
delete_old.put(old_key, FieldValue.delete());
batch.update(docRef, new_map);
batch.update(docRef, delete_old);
}
}
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
} else {
// ... "Error updating field -> " + task.getException()
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// ... "Failure getting notices -> " + e
}
});
}
Just wanted to share because I read that you were hoping for a Firestore based solution.
This worked for me. forEach will query each document in the collection and you can manipulate as you like.
db.collection("collectionName").get().then(function(querySnapshot) {
querySnapshot.forEach(async function(doc) {
await db.collection("collectionName").doc(doc.id).set({newField: value}, {merge: true});
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});
To solve this, you need to update each user to have the new property and for that I recommend you to use a Map. If you are using a model class when you are creating the users as explained in my answer from this post, to update all users, just iterate over the users collection amd use the following code:
Map<String, Object> map = new HashMap<>();
map.put("timestamp", FieldValue.serverTimestamp());
userDocumentReference.set(map, SetOptions.merge());
I am guessing that last_login is a primitive data type, maybe a long to hold a timestamp. An auto-generated setter would look like this:
private long last_login;
public void setLast_login(long last_login) {
this.last_login = last_login;
}
This leads to a crash when old documents that lack the field are fetched due to null assignment to a variable of a primitive data type.
One way around it is to modify your setter to pass in a variable of the equivalent wrapper class - Long instead of long in this case, and put a null check in the setter.
private long last_login;
public void setLast_login(Long last_login) {
if(last_login != null) {
this.last_login = last_login;
}
}
The cost of avoiding the null pointer exception is the boxing-unboxing overhead.
I'm having trouble with checking if my collections exists in Firestore database.
When I was working with Firebase Realtime database i could have used:
if(databaseSnapshot.exists)
Now with Firestore I wanna do the same.
I have already tried
if (documentSnapshots.size() < 0)
but it doesn't work.
Here is the current code:
public void pullShopItemsFromDatabase() {
mShopItemsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
ShopItem shopItem = document.toObject(ShopItem.class);
shopItems.add(new ShopItem(shopItem.getImageUrl(), shopItem.getTitle(), shopItem.getSummary(), shopItem.getPowerLinkID(), shopItem.getlinkToShopItem(),shopItem.getLinkToFastPurchase(), shopItem.getKey(), shopItem.getPrice(),shopItem.getVideoID()));
}
if (shopItems != null) {
Collections.sort(shopItems);
initShopItemsRecyclerView();
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
setNothingToShow();
}
}
});
}
the function: setNothingToShow();
Is actually what I wanna execute if my collection is empty / doesn't exists.
Please advise!
Thanks,
D.
Use DocumentSnapshot.size() > 0 to check if the collection exists or not.
Here is an example from my code:
db.collection("rooms").whereEqualTo("pairId",finalpairs)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if(task.getResult().size() > 0) {
for (DocumentSnapshot document : task.getResult()) {
Log.d(FTAG, "Room already exists, start the chat");
}
} else {
Log.d(FTAG, "room doesn't exist create a new room");
}
} else {
Log.d(FTAG, "Error getting documents: ", task.getException());
}
}
});
exists() applies to DocumentSnapshot while you're dealing with QuerySnapshot
Call task.result for getting QuerySnapshot out of Task<QuerySnapshot>.
From that, call result.getDocuments() and iterate through each of the DocumentSnapshot calling exists() on them.