我有这个数据库
我阅读了密钥“20160877”来更新类型这很容易,因为只有一个密钥。 通过这种方式==>
table_user.child("20160877").child("type").setValue("2");
如果我放了很多像“20160877”这样的键并且里面有值,并且想要更新所有键中所有类型的类型,我该怎么做?
我尝试过这种方式但它创建了新密钥然后更新其中的类型,我想更新现有数据而不是创建新数据
DatabaseReference table_user;
FirebaseDatabase database;
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_main);
database = FirebaseDatabase.getInstance();
table_user = database.getReference("Users");
}
public void current_member(View view) {
table_user.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
id =snapshot.getKey();
table_user.child(id).child("type").setValue("1");
Toast.makeText(AdminMainActivity.this, "تم تفعيل صفحة الاعضاء الحاليون", Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public void active_C_page(View view) {
table_user.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
id =snapshot.getKey();
table_user.child(id).child("type").setValue("2");
Toast.makeText(AdminMainActivity.this, "تم تفعيل صفحة الترشح", Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
答案 0 :(得分:1)
如果您想更新所有用户的状态,您需要遍历 snapshot
中 onDataChange
中的用户节点。
比如:
table_user.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot: snapshot.getChildren()) {
id = userSnapshot.getKey();
table_user.child(id).child("type").setValue("1");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
或者直接从userSnapshot
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot: snapshot.getChildren()) {
userSnapshot.getReference().child("type").setValue("1");
}
}