I have this data structure in Firestore as shown in the image.
I am using FirestoreRecyclerOptions
to display user`s addresses. I am storing the address as POJO (UserAddressModel.java), I do not know if it the best practice or not to store it that way or not but that how I did it.
UserInformationsModel.java
public class UserInformationsModel {
private String email, username, name ;
private UserAddressModel userAddress;
private String phoneNumber;
private String photo;
private String photoUrl;
public UserInformationsModel() {
}
}
UserAddressModel.java
public class UserAddressModel {
private String fullName, streetAddressOne, streetAddressTwo, city, state, country;
private String zipCode;
public UserAddressModel() {
}
public UserAddressModel( String streetAddressOne, String city, String state, String country, String zipCode) {
this.streetAddressOne = streetAddressOne;
this.city = city;
this.state = state;
this.country = country;
this.zipCode = zipCode;
}
public String getFullName() {
return fullName;
}
public String getStreetAddressOne() {
return streetAddressOne;
}
public String getStreetAddressTwo() {
return streetAddressTwo;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getCountry() {
return country;
}
public String getZipCode() {
return zipCode;
}
I have already created the AdapterAddress class that extended FirestoreRecyclerAdapter and it`s layout.
My question is how to display address1 and address2 in my recyclerview ?
Because I am notice that setQuery
method require a query but i do not know how to get the addresses
Query query = coll_ref.orderBy("?????");
FirestoreRecyclerOptions<UserAddressModel> options = new FirestoreRecyclerOptions.Builder<UserAddressModel>()
.setQuery(query, UserAddressModel.class)
.build();
adapterAddress = new AdapterAddress(options);
There is no way you can get those addresses using a query. FirestoreRecyclerOptions
object require a Query
or a CollectionReference
to be passed to the setQuery()
method when you need to get all documents within a collection or when you need to filter them.
What you need to do is to get a reference on the user document and make a get()
call:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.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()) {
Map<String, Object> map = document.getData();
}
}
}
});
See, document.getData()
returns a map. Simply ieterate through the map and get the addresses.