我100%保证正在填充ArrayList,因为当我进入调试模式时,我可以看到正确添加了元素。
但在完成onDataChange块位置后,ArrayList为空。
这是我的代码,我将不胜感激任何想法:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
public ArrayList<LocationObject> locations = null;
FirebaseDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
database = FirebaseDatabase.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locations = new ArrayList<>();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
final DatabaseReference ref = database.getReference("venues");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
locations.add(d.getValue(LocationObject.class));
}
Log.d("ELEMENT", String.valueOf(locations.size()));
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("ERROR", "Connection failed");
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d("SIZE", String.valueOf(locations.size()));
//Log.d("SIZE:", String.valueOf(locations.size()));
mMap = googleMap;
if(locations.size() != 0) {
for (LocationObject o : locations) {
double lat = o.getLat();
double lng = o.getLoong();
LatLng place = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(place).title(o.getDesc()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
}
}
else{
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
}
答案 0 :(得分:3)
addValueEventListener和onMapReady是异步函数,onMapReady可以在addValueEventListener之前完成。