I am using Cloud Firestore and there is a array data in field. So how can I get data from array individually?
Asked
Modified
5 years, 5 months ago
Viewed
7k times
Part
of Mobile Development and Google Cloud Collectives
1 Answer
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]
4 Comments
Arvind Kumar
Thanx @Alex Mamo. It is working. But how did you know the collection & document name, however I have wrapped it in the image.
Latief Anwar
second solution above, i got warning "Unchecked cast: 'java.lang.Object' to 'java.util.ArrayList<java.lang.String>'"
Alex Mamo
@LatiefAnwar You can use an annotation to suppress it.
