Michal Michal - 3 months ago 110
Android Question

Retrieving data from Firebase Android Studio

Structure of my Firebase Datebase looks like that:

enter image description here

I want to retrieve data from it in such a manner that when I change the value of the "Name" in database it will instantly change in Android Studio. Right now, I use

.addChildEventListner
method combined with
Map<String, String>
. Could someone help me ?

Edit: My code:

Firebase markerRef = myFirebaseRef.child("marker");

markerRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
double latitude = Double.parseDouble(map.get("Lat"));
double longitude = Double.parseDouble(map.get("Lon"));
LatLng location = new LatLng(latitude, longitude);

String filename = map.get("Name");
String[] splitString = filename.split(",");


mMap.addMarker(new MarkerOptions()
.position(location)
.title(splitString[0])
.snippet(splitString[1])
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}

@Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {


}

@Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(FirebaseError firebaseError) {

}
});

Answer

In your activity create empty HashMap Hasmap<String, Marker> markers = new Hashmap<>(); Then in onChildAdded

Marker m = mMap.addMarker(new MarkerOptions()
                        .position(location)
                        .title(splitString[0])
                        .snippet(splitString[1])
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
markers.add.put(dataSnapshot.getKey(), m);

And in onChildChanged

Marker m = markers.get(dataSnapshot.getKey());
m.setPosition(newLocation);
//And anything else, that changing

And finally in onChildRemoved

markers.get(dataSnapshot.getKey()).remove();
markers.remove(dataSnapshot.getKey());
Comments