Reputation: 29
So I have a collection in Cloud Firestore and I need to store the informations from database in a list (coordPlaces). I did it like this, created these methods:
private void readData(FirestoreCallback firestoreCallback){
db.collection("AddPlaces")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
if(task.getResult() != null){
List<ListPlacesModel> list = task.getResult().toObjects(ListPlacesModel.class);
for(ListPlacesModel model : list)
{
LatLng place = new LatLng(model.getPlaceLat(), model.getPlaceLng());
coordPlaces.add(place);
String name = model.getPlaceName();
gMap.addMarker(new MarkerOptions().position(place).title(name));
}
firestoreCallback.onCallback(coordPlaces);
}
}
else {
Log.d("ERROR", String.valueOf(task.getException()));
}
}
});
}
private interface FirestoreCallback{
void onCallback(List<LatLng> myList);
}
And then called the method like this:
db = FirebaseFirestore.getInstance();
readData(new FirestoreCallback() {
@Override
public void onCallback(List<LatLng> myList) {
});
I've saw this solution in this video.
But now I need to access this list in order to creathe a 2D array out of it, in this manner:
for(int i=0;i<coordPlaces.size();i++)
{
for(int j=0;j<coordPlaces.size();j++)
{
int distance = (int) SphericalUtil.computeDistanceBetween(coordPlaces.get(i), coordPlaces.get(i+1));
graph[i][j] = distance;
}
}
Anywhere in the code where I put these 2 for loops, my app crashes. I can't find a solution of how to create this 2D array. Any ideas?
Upvotes: 0
Views: 128
Reputation: 138824
The only places where you should add those lines of code should be either inside onComplete()
or if you're using a custom callback inside onCallback()
. If you place those lines in any other parts of your class, you'll get an empty list, hence that IndexOutOfBoundsException.
If you don't want to use that approach, you might also consider using a LiveData object, as it's a type of object that can be observed. If you understand Kotlin, the following resource will help:
Upvotes: 3