尝试从Firebase实时数据库检索数据时未调用onDataChange

时间:2019-11-18 16:38:26

标签: android firebase-realtime-database

我正在尝试从Realtime Firebase数据库接收所有数据。我想遍历这些数据并将其存储到Event对象中。除此之外,我还将这些对象存储到事件的ArrayList中。

我需要这些事件,因为我想在Google地图上放置这些事件的标记。但是,当我只运行应用程序时,标记不会显示,因为未调用OnDataChanged方法。我已经尝试调试我的代码,但是我对此仍然很陌生,所以我可能做错了什么。

我是Realfire Firebase数据库的新手,所以我可能缺少一些东西。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapsActivity";
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

//Location
GoogleMap mGoogleMap;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
Marker marker;
FusedLocationProviderClient mFusedLocationClient;

//Firebase data
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;

ArrayList<Event> events;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    events = new ArrayList<>();
    getData();
    placeMarkers();

}
public void getData(){
    FirebaseDatabase.getInstance().getReference().child("events").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()){
                String name = ds.child("name").getValue(String.class);
                String organisator = ds.child("organisator").getValue(String.class);
                String date = ds.child("date").getValue(String.class);
                String startHour = ds.child("startHour").getValue(String.class);
                String location = ds.child("location").getValue(String.class);
                String description = ds.child("description").getValue(String.class);
                LatLng latLng = new LatLng(ds.child("latLng").child("latitude").getValue(Double.class), ds.child("latLng").child("longitude").getValue(Double.class));

                Event event = new Event(name, organisator, date, startHour, location, description, latLng);
                events.add(event);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

public void placeMarkers() {
    ArrayList<Event> evenementen = new ArrayList<>(events);

    for (Event event : evenementen) {

        MarkerOptions eventMarker = new MarkerOptions();
        eventMarker.position(event.getLatLng());
        eventMarker.title(event.getName());
        marker = mGoogleMap.addMarker(eventMarker);
    }
}

1 个答案:

答案 0 :(得分:0)

很明显,我的问题与Firebase异步工作有关(我对此不太了解),但是我遵循了本指南https://www.youtube.com/watch?v=OvDZVV5CbQg,现在一切正常。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapsActivity";
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

//Location
GoogleMap mGoogleMap;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
Marker marker;
FusedLocationProviderClient mFusedLocationClient;

//Firebase data
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference firebaseRootRef;
private DatabaseReference eventsRef;
ArrayList<Event> events;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mFirebaseDatabase = FirebaseDatabase.getInstance();
    firebaseRootRef = mFirebaseDatabase.getReference();
    eventsRef = firebaseRootRef.child("events");
    events = new ArrayList<>();

    readData(this::placeMarkers);


}

private interface FirebaseCallback {
    void onCallback(List<Event> events);
}

private void readData(FirebaseCallback firebaseCallback){
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()){
                String name = ds.child("name").getValue(String.class);
                String organisator = ds.child("organisator").getValue(String.class);
                String date = ds.child("date").getValue(String.class);
                String startHour = ds.child("startHour").getValue(String.class);
                String location = ds.child("location").getValue(String.class);
                String description = ds.child("description").getValue(String.class);
                LatLng latLng = new LatLng(ds.child("latLng").child("latitude").getValue(Double.class), ds.child("latLng").child("longitude").getValue(Double.class));

                Event event = new Event(name, organisator, date, startHour, location, description, latLng);
                events.add(event);
            }
            firebaseCallback.onCallback(events);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };
    eventsRef.addListenerForSingleValueEvent(valueEventListener);
}


public void placeMarkers(List<Event> eventList) {
    for (Event event : eventList) {

        MarkerOptions eventMarker = new MarkerOptions();
        eventMarker.position(event.getLatLng());
        eventMarker.title(event.getName());
        marker = mGoogleMap.addMarker(eventMarker);
    }
}