我试图将一些数据插入我的firebase但遇到以下错误,第二个数据丢失了。以下是代码:
Firebase.setAndroidContext(this);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
//Getting values to store
String name = mName.getText().toString().trim();
String address = mAddress.getText().toString().trim();
String latlng = mLatLng.getText().toString().trim();
//Creating Person object
FM_Spots spots = new FM_Spots();
//Adding values
spots.setName(name);
spots.setAddress(address);
spots.setLatLng(latlng);
//Storing values to firebase
//ref.child("FM_Spots").setValue(spots);
Firebase newRef = ref.child("FM_Spots").push();
newRef.setValue(spots);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
我只有2个字段是名称,地址是来自最后一个字段(latlng)的数据。请指教,谢谢。
-sea -
答案 0 :(得分:0)
当你说"第二个数据"你的意思是缺少可写对象的第二个字段,对吗?
如果是这样,您可以使用updateChildren(Map map)方法而不是setValue()来指定要直接写入的字段:
newRef.updateChildren(convertFMSpotsToMap(spots));
其中convertFMSpotsToMap()是这样的:
private static Map<String, Object> convertFMSpotsToMap(@NonNull FM_Spots spots) {
HashMap<String, Object> map = new HashMap<>();
map.put("name", spots.getName());
map.put("address", spots.getAddress());
return map;
}