【发布时间】:2015-09-27 18:46:46
【问题描述】:
似乎我的onChildAdded() 方法在我使用updateChildren() 方法时不起作用。它适用于push().setValue() 方法。
这两种方法都可以很好地向 Firebase 发送数据。
有什么想法吗?
谢谢!
这是push() 方法(有效)
private void saveToFirebase() {
String username = getIntent().getStringExtra("Username");
//takes string user input and creates a child of Gaben(parent)
Firebase usersRef = myFirebaseRef.child(username);
//sub child
Firebase location = usersRef.child("details");
Map mLocations = new HashMap();
mLocations.put("timestamp", mLastUpdateTime);
Map mCoordinate = new HashMap();
myFirebaseRef.push().setValue(mLocations);
}
private void drawLocations() {
// Get only latest logged locations - since 'START' button clicked
Query queryRef = myFirebaseRef.orderByChild("timestamp").startAt(startLoggingTime);
// Add listener for a child added at the data at this location
queryRef.addChildEventListener(new ChildEventListener() {
LatLngBounds bounds;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map data = (Map) dataSnapshot.getValue();
String timestamp = (String) data.get("timestamp");
// Get recorded latitude and longitude
Map mCoordinate = (HashMap) data.get("location");
double latitude = (double) (mCoordinate.get("latitude"));
double longitude = (double) (mCoordinate.get("longitude"));
// Create LatLng for each locations
LatLng mLatlng = new LatLng(latitude, longitude);
// Make sure the map boundary contains the location
builder.include(mLatlng);
bounds = builder.build();
//get username input from login activity
String username = getIntent().getStringExtra("Username");
MarkerOptions mMarkerOption = new MarkerOptions()
// Add a marker for each logged location
.position(mLatlng)
.title(username)
.snippet(timestamp)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
Marker nMarker = mMap.addMarker(mMarkerOption);
nMarker.showInfoWindow();
// Zoom map to the boundary that contains every logged location
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, MAP_ZOOM_LEVEL));
}
});
}
这是不起作用的update()方法
private void saveToFirebase() {
String username = getIntent().getStringExtra("Username");
//takes string user input and creates a child of Gaben(parent)
Firebase usersRef = myFirebaseRef.child(username);
//sub child
Firebase location = usersRef.child("details");
Map mLocations = new HashMap();
mLocations.put("timestamp", mLastUpdateTime);
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
//updates location in firebase
location.updateChildren(mLocations);
location.updateChildren(mCoordinate);
}
基本上唯一的区别是 push 方法每次都会创建唯一的 id,而另一个只是更新它。
唯一的区别是这几行
location.updateChildren(mCoordinate);
还有这个
myFirebaseRef.push().setValue(mLocations);
【问题讨论】: