我有一个包含自动生成主键的数据库。 看这里:
data
------0
-----------id
-----------name
------1
-----------id
-----------name
等等。
我不知道主键,我想通过特定ID更新名称。我怎么能这样做?
答案 0 :(得分:3)
首先创建一个类
public class User {
int id;
String name;
public User(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然后获取要更新的db对象
DatabaseReference dbRef = firebaseDatabase.getReference("YOUR_DB_NAME");
Query query = dbRef
.orderByChild("id")
.equalTo("ID_OF_THE_USER");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Log.d(TAG, dataSnapshot1.getKey() + " " + dataSnapshot1.getValue(Profile.class)
.toString());
updateUser(dataSnapshot1.getKey(),"ID_OF_THE_USER", "New_Name");
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void updateUser(DatabaseReference db,int key, String id, String name,) {
User user = new User(id, name);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/data/" + key, postValues);
db.updateChildren(childUpdates);
}
希望它能帮到你......