I have an array with my object and Cloud Firestore. In Firestore I have 11 documents with two fields each. I take data from the cloud and set the values of the two fields in an Object that I created called Food.
Then I want to read the value of the name
field of each element in the array but Android give me NullPointerException
because I'm calling the method getName()
on a null object.
Before I also tried using an HashMap instead of an Array but the result is the same, call to the elements give me the same exception.
Here is the last version of my code :
Food[] foodList = new Food[11];
cloudDatabase.collection("food").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
Food food;
int counter = 0;
for(QueryDocumentSnapshot foodDocument : task.getResult()) {
if (counter<12) {
String foodName = foodDocument.get("name").toString();
float foodPrice = Float.valueOf(foodDocument.get("price").toString());
food = new Food(foodName, foodPrice);
foodList[counter] = food;
food = null;
counter++;
}
else {
Log.w("Food Counter", "Limit reached!");
}
}
}
});
for (Food foodElement : foodList) {
String name = foodElement.getName(); //here I get the NullPointerException
Log.d("Food Names", name);
}
I searched many things but I still didn't found the soluction. What do you suggest to do? Can it be a problem of the CompleteListener
of Firestore?
Many Thanks!