How to fetch sub-collection data from firestore - android

I have a collection called TripInfo following with user's id and then I have created subcollection with auto generate id for each doc. The problem is I can't fetch the data using the following code:
private void checkDataExistingDate() {
db.collection("TripsInfo").document(UID).collection("Individual_Trip").document()
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.getResult().exists()){
DocumentSnapshot snapshot = task.getResult();
Map<String, Object> map = snapshot.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(Tag, "All data"+entry.getValue().toString());
}
}
}
});
Or do I need to store the without subcollection? In Realtime we were using push to generate auto-id, but here I don't know what is the equivalent to create a key after placing the user's id in the document.

Suppose you have store userid with uid parameter in TripsInfo collection and also have Individual_Trip as subcollection in 'TripsInfo' collection. you can fetch subcollection like this.
FirebaseFirestore.getInstance().collection("TripsInfo")
.get()
.addOnCompleteListener(
new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (FirebaseAuth.getInstance().getUid().equalsIgnoreCase(document.getString("uid"))) {
document.getReference()
.collection("Individual_Trip")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
list = task.getResult().toObjects(Individual_Trip.class);
showListOfRequest();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
hideProgress();
}
});
break;
}
}
}
}
});
FirebaseAuth.getInstance().getUid().equalsIgnoreCase(document.getString("uid"))
this line is for checking for userid, when you have multiple data in your 'TripsInfo' collection.
you can also use whereEqualTo for that, FirebaseFirestore.getInstance().collection("TripsInfo")
.whereEqualTo("userId", "uid").get()...

Related

Get array from Firestore Kotlin [duplicate]

I am using Cloud Firestore and there is a array data in field. So how can I get data from array individually?
To get the values within ip_range array, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collection("aic").document("ceo").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> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("ip_range")) {
Log.d("TAG", entry.getValue().toString());
}
}
}
}
}
});
Another approach would be:
rootRef.collection("products").document("06cRbnkO1yqyzOyKP570").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
ArrayList<String> list = (ArrayList<String>) document.get("ip_range");
Log.d(TAG, list.toString());
}
}
}
});
In both cases, the output in your logcat will be:
[172.16.11.1, 172.16.11.2]

How to iterate a Firestore collection on Android?

I have a Firestore collection like this:
Take a look at kost collection. There are 4 docouments in it, and each document has the following fields: fasilitas, gender, harga, etc
For each document, I want to retrieve all the fields.
Now I have this:
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
DocumentReference docRef = firestore.collection("kost").document();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
for (DocumentSnapshot ds:task.getResult()){
}
}
}
});
It's not even a correct code, task.getResult() is underlined:
foreach not applicable to type
'com.google.firebase.firestore.DocumentSnapshot
What's the correct way, then?
Your problems is in this code:
DocumentReference docRef = firestore.collection("kost").document();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
Your docRef points to a new, empty document. What you want instead is to point to the entire collection as shown in the documentation on reading all documents in a collection:
db.collection("kost")
.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());
}
}
});

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

how to get root document fields of collection in firestore android

I want to get the document fields of the root collection in android firestore
my database structure in firestore is
collection
documents-->root fields
collection
documents-->fields
now i want to get root fields. How to do that in android firestore?
firestore.collection("Players").orderBy("deptName").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//model class
Example example=document.toObject(Example.class);
exampleList.add(example);
}
Toast.makeText(getActivity(), ""+exampleList, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), ""+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
use this line document.getId();
firestore.collection("Players").orderBy("deptName").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//model class
Example example=document.toObject(Example.class);
example.setDocID(document.getId());
exampleList.add(example);
}
Toast.makeText(getActivity(), ""+exampleList, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), ""+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
https://firebase.google.com/docs/firestore/query-data/get-data#java_2

How to avoid index in firestore?

I have created a database in firestore and loaded the test data successfully. But later I noticed that some data is missing in database. I found that when I load the same records with a different value for some fields the old record is replaced with the new record. I feel like this is the issue in the database design. I need to collect and save all the records even if it is a duplicate records at entire records level.
Could you please let me know how to do this ?
private void exportToFireStore() {
// Access a Cloud Firestore instance from your Activity
final FirebaseFirestore db = FirebaseFirestore.getInstance();
/* ----------------_-------Collection delete is not supported-----------------------
----------Hence get all the document (coins) for individual Docs delete----------
*/
//------------------------------- Getting document (coins) Ends ---------------------------------------------
final List<String> coinsFromFirestore = new ArrayList<>();
db.collection("cryptos").document(userEmailID).collection("coin")
.whereEqualTo("createdBy", userEmailID)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
System.out.println("Testing 1 Batch Read done" + document.getData());
coinsFromFirestore.add(document.getData().get("coinname").toString());
}
//------------------------------- Getting document (coins) Ends ---------------------------------------------
if(coinsFromFirestore.size()>0){
for (int i=0;i<coinsFromFirestore.size();i++) {
if ( i<(coinsFromFirestore.size()-1) ) {
db.collection("cryptos").document(userEmailID).collection("coin").document(coinsFromFirestore.get(i))
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
System.out.println("Testing 1 Successfully Deleted the document " );
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
System.out.println("Testing 1 Error Deleting the document ");
}
});
}else{
db.collection("cryptos").document(userEmailID).collection("coin").document(coinsFromFirestore.get(i))
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
addTranToFireBaseeNow(db);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! For last coin Ends !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
}else{
addTranToFireBaseeNow(db);
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
//------------------------------- Getting document (coins) Ends ---------------------------------------------
}
private void addTranToFireBaseeNow(FirebaseFirestore db) {
WriteBatch batch = db.batch();
DocumentReference newCoinRef;
//CollectionReference cryptos = db.collection("cryptos");
List<Tran> tranList = getAllTranForFireStore();
String firebaseUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
for (Tran t : tranList) {
Map<String, Object> tranData = new HashMap<>();
tranData.put("firebaseid", firebaseUID);
tranData.put("createdBy", userEmailID);
tranData.put("coinid", t.getCoinID());
tranData.put("coinname", t.getCoinName());
tranData.put("coinsymbol", t.getCoinSymbol());
tranData.put("date", String.valueOf(t.getDate()));
tranData.put("qty", String.valueOf(t.getQty()));
tranData.put("price", String.valueOf(t.getPrice()));
tranData.put("priceunit", String.valueOf(t.getPriceUnit()));
newCoinRef= db.collection("cryptos").document(userEmailID).collection("coin").document(t.getCoinName());
batch.set(newCoinRef, tranData);
}
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
}
No index is setup for my DB
Since you are using set without any options, it will overwrite the existing data. But your requirement is to merge your data, so you have to use the merge option as follows:
batch.set(newCoinRef, tranData, SetOptions.merge());
You can read more about options here.
Furthermore there is a good post which lists the differences between set, update and create.
You can use update and change one variable
reference.document("documentname").update("field", variable)
or
reference.document("documentname").set({
field: variable
}, { merge: true });
Or.. if you have to update an entire object, you can use:
reference.document("documentname").set(newObject, { merge: true });
Check this article:
https://saveyourtime.medium.com/firebase-cloud-firestore-add-set-update-delete-get-data-6da566513b1b

Categories

Resources