I'm struggling with the Firestore because there is not enough documentation which can describe all the possible working scenario of Firestore.
Let me explain my requirement.
I have the following GUI in android:
- EditText. (Name)
- Spinner. (cities)
- Spinner. (Busses)
- Add Button
The Firestore have the collections as the following:
- cities (which contain the multiple cities)
- busses (which contain the multiple busses)
- user ( which will contain the username, buss reference, city reference)
Now the problem is that when user click on the Add Button, first I have to get the reference of selected city
and selected bus
then add the these three values to user
collection but to get the reference I have to call the following code.
final Map<String, Object> data = new HashMap<>();
data.put("username", editText.getText().toString());
db.collection("cities")
.whereEqualTo("name", city) // get city by name
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot query) {
data.put("city", query.getDocuments().get(0).getReference());
// once the city reference got, then get the Buss reference
db.collection("busses")
.whereEqualTo("busnumber", bus) // get bus by number
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot query) {
data.put("bus", query.getDocuments().get(0).getReference());
addData(data); // now the city and bus reference got, add the data now.
}
});
}
});
This make the app little slow, and looks like stupid approach, I want to confirm is it the correct approach? or is there better way to do this? or in future may be I have to get the more reference then more nested calls?
Edited
Further more this is really stupid way that I have to recall these code again and again to get the reference of city
or bus
so a lot of duplication will be in my application, which is not good. So I want to create two methods getCityRefByName(String name)
and getBusRefByNUmber(int number)
as the following.
public DocumentReference getBusByNumber(int number){
db.collection("busses")
.whereEqualTo("busname", number)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot query) {
query.getDocuments().get(0).getReference(); // return this reference, How?
}
});
}
public DocumentReference getCityRefByName(String name){
db.collection("cities")
.whereEqualTo("name", name)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot query) {
query.getDocuments().get(0).getReference(); // return this reference, How?
}
});
}
The Firestore documentation is not good enough that's why I'm facing these stupid core problems.