我正在使用这个代码来更新Firebase上的数据,但它是新的.我尝试了很多代码,并且使用相同键的新的代码,除了最后一个字符.
我用这个作为Firebase网站推荐,但它不工作.我创建了一个新的下一次更新:
Map<String,Object> childUpdate = new HashMap<>(); childUpdate.put("/masjeds/" + masjed.getId(),masjed.toMap()); reference.updateChildren(childUpdate);
而这段代码也是一样的
final FirebaseDatabase database = FirebaseDatabase.getInstance(); masjeds = database.getReference("masjeds"); reference.child(masjed.getId()).setValue(masjed,new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError,DatabaseReference databaseReference) { // Toast.makeText(MyMasjedsActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show(); } });
Masjed类是纯java对象
public class Masjed { private String userID; private String id; private String name; private String address; private String phone; private boolean matloopEmam; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public boolean isMatloopEmam() { return matloopEmam; } public void setMatloopEmam(boolean matloopEmam) { this.matloopEmam = matloopEmam; } public Masjed(String name,String address,String phone) { this.name = name; this.address = address; this.phone = phone; } public Masjed() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Map<String,Object> toMap() { Map<String,Object> map = new HashMap<>(); map.put("name",name); map.put("address",address); map.put("phone",phone); map.put("id",id); map.put("userID",userID); return map; } }
id是我假设push.getkey并将其作为ID的问题
那么使用push.setValue(masjed)将使用相同的键
事实证明,当我使用它的dosnt存在时,它并不总是Case的改变,所以它创建了一个帮助我的答案是Chester Answer
解决方法
我希望这有助于,在我的宠物项目中使用它(这不是清洁的解决方案,但它的工作原理):
masjeds = database.getReference("masjeds"); ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { masjedKey = dataSnapshot1.getKey(); // This is a member variable masjed = dataSnapshot1.getValue(Masjed.class); // This is a member variable } } @Override public void onCancelled(DatabaseError databaseError) { } }; masjeds.orderByChild("id").equalTo(masjed.getId()).addValueEventListener(listener); //Use your Map to update each value this is just an example masjeds.child(masjedKey).child("name").setValue("John"); //you can add event listener if you want to see if it's completed,but it works without the events