I have tried to get data from Firebase database and save the data into a global variable(mExampleHashMap) so that I can use it other places like on windowinfoclick listener. However, the data is only valid in the event listener, and I cannot get those data out of it. Seems it is related with variable scope so I tried to make it final on that global variables but still doesnt work. How can I save data in anonymous interface to local main variables?
final HashMap<Marker, Example> mExampleHashMap = new HashMap<>();
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// Get data from firebase database
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference();
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String name = (String) d.child("example").getValue();
String x = (String) d.child("x").getValue();
String y = (String) d.child("y").getValue();
mExample = new Example(example, x, y);
if (mExample != null) {
Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(x), Double.parseDouble(y))).title(name));
mExampleHashMap.put(marker, mExample );
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// When I tried to use data out of the event listener, the variable is empty.
Log.d(TAG, "onMapReady: mExampleHashMap: " + mExampleHashMap.size());
}