我想使用Android应用程序更改Firebase数据库中的数据。所以我希望它在打开时为true,在关闭时为false。 (0-states-001-True / False)因此,当我按下切换按钮时,我想更新数据(true / false)。我分享了下面的代码。如何更新数据?这些代码不起作用,数据错误。 database application
DatabaseReference dbProducts1 = FirebaseDatabase.getInstance().getReference("0").child("states").child("001");
dbProducts1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if(dataSnapshot1.exists()){
for(DataSnapshot productSnapshot : dataSnapshot1.getChildren()){
Product1 p1 = productSnapshot.getValue(Product1.class);
productList.add(p1);
}
adapter = new ProductsAdapter(MainActivity.this, productList);
recyclerView.setAdapter(adapter);
}
}
public class Product1 extends Product {
private boolean states;
public Product1(){
}
public Product1(boolean states) {
this.states = states;
}
public boolean getStates() {
return states;
}
}
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
// holder.textViewID.setText(String.valueOf(product.getid()));
holder.viewStatus.setText(String.valueOf(product.getStates()));
}
class ProductViewHolder extends RecyclerView.ViewHolder {
ToggleButton viewStatus;
public ProductViewHolder(View itemView) {
super(itemView);
viewStatus = itemView.findViewById(R.id.toggle_Data);
}
}
答案 0 :(得分:0)
尝试在开关状态更改时进行更新
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = mDatabase.child("states").child("001")
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Map<String, Object> newStatus = new HashMap<>();
childUpdates.put("states", isChecked)
ref.update(newStatus)
}
});
答案 1 :(得分:-1)
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("status/001");
if(isChecked){
myRef.setValue(true);
}else{
myRef.setValue(false);
}
}
});