Looping over Firestore to get document ids - android

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());
}

Related

Get Specific Field from Firestore with whereEqualTo

I have a firebase document and i want to extract fields values to TextView in adnroid where the currentuser id from mAuth equals the user-id field inside the document but it's not working
Firebase Document Image
db = FirebaseFirestore.getInstance();
db.collection("users")
.whereEqualTo("user-uid",uid)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
user_name = task.getResult().getString("user-name");
user_email = task.getResult().getString("user-email");
user_last_name = task.getResult().getString("user-last-name");
user_phone_number = task.getResult().getString("user-phone-number");
}
});
db.collection("users")
.whereEqualTo("user-uid",uid)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(),"success accessing database",Toast.LENGTH_SHORT).show();
for (QueryDocumentSnapshot document : task.getResult()){
//Fetch from database as Map
user_name = (String) document.getData().get("user-name");
user_last_name =(String) document.getData().get("user-last-name");
user_phone_number =(String) document.getData().get("user-phone-number");
user_email =(String) document.getData().get("user-email");

Android How to sort data that i retrieve from Database

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();
}
}
});

How can I retrieve all the collection data users saved from Firebase Database using android studio?

I want to retrieve and show Collection data saved in Firebase database on the android screen.
I get three types of information(orders, quantity, date) from the users and save them on the database using :
OrderInfo orderInfo = new OrderInfo(orderText, quantityText, dateText);
db.collection("orders").document(user.getUid()).set(orderInfo)
And now I want to retrieve all the data(orderText, quantityText, dateText)
saved in collection "orders" maybe in the form of list.
How can I do that?
To get the values of your orderText, quantityText and dateText properties within a single OrderInfo object, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference ordersRef = rootRef.collection("orders");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
ordersRef.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()) {
OrderInfo orderInfo = document.toObject(OrderInfo.class);
Log.d(TAG, orderInfo.getOrderText() + " / " + orderInfo.getQuantityText() + " / " + orderInfo.getDateText());
}
}
}
});
If you want to get all OrderInfo objects within your orders collection, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference ordersRef = rootRef.collection("orders");
ordersRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<OrderInfo> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
OrderInfo orderInfo = document.toObject(OrderInfo.class);
list.add(orderInfo);
}
//Do what you need to do with your list
}
}
});

how to get auto generate id of a document in cloud firestore?

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

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());
}
}
});

Categories

Resources