'retrieving data from cloud firestore
Hi im trying to retrieve values from a cloud firestore document in a collection based on a string query to filter the keys but cant seem to find any help online. Please assist or direct to existing solutions. Thanks. this is in java as well.
- I havent tried anything yet as I'm not too sure what functions provide this
im trying to filter a collection called food emissions with the key from this function
UPDATE
ive retrieved the data from the firestore collection and stored in a hashmap called food data. im now trying to filter this hashmap based on a string stored in the variable key and assign the value that matches to the variable co2EqTemp. however when I make a toast of the value thats stored in co2EqTemp it just says it is referencing a null value
private void addMeal() {
mealname = mealName.getText().toString();
if(mealname.isEmpty()){
mealName.setError("Please name your meal!");
mealName.requestFocus();
return;
}
String UserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase fDatabase = FirebaseDatabase.getInstance();
fDbRef = fDatabase.getReference("MealLists");
for(Map.Entry<String,Double> entry: food.entrySet()){
key = entry.getKey();
values = entry.getValue();
foodAmount = values.toString();
mealData meals = new mealData(key, UserID, foodAmount);
fDbRef.child(mealname).setValue(meals);
makeToast(mealname);
foodRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
Map<String, Object> map = task.getResult().getData();
for(Map.Entry<String, Object> entry : map.entrySet()){
foodData.put(entry.getKey(),entry.getValue());
}
for(Map.Entry<String, Object> entry: foodData.entrySet()){
if (entry.getKey().equals(key)){
Co2eqTemp = (Double) entry.getValue();
}
Co2eq = Co2eq + Co2eqTemp;
}
}
}
});
}
storeMeal();
}
});
Solution 1:[1]
ok so I fixed this by just avoiding the hashmap completely and filtering the data returned from the collection like this.
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
Map<String, Object> map = task.getResult().getData();
for(Map.Entry<String, Object> entry : map.entrySet()){
if(entry.getKey().equals(key)) {
Double co2 = Double.parseDouble(entry.getValue().toString());
Co2eqTemp = co2 * values;
}
Co2eq = Co2eq + Co2eqTemp;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Phoebe Baldwin |
