I want to remove the string "childid1" from the list containing "chilidid1,childid2,childid3,..." From firebase realtime
I want to remove the string "childid1" from the list containing "chilidid1,childid2,childid3,..." From firebase realtime
CodePudding user response:
I guess that database you made is for learning how a real time database works on firebase.
Your database strtucture is wrong. You should redo-it and make it like this:
-classid1
-children:
-child1: ""
-child2: ""
You cannot have multiple values in a child key unless it is a list. In that case, you need to create a DatabaseReference that gets the value and classifies it to a list, then you do whatever you want with that list and then post it back to the database. Example:
DatabaseReference childsRef = FirebaseDatabase.getInstance().getReference().child("classes").child("classid1");
childsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
ArrayList[] childrenList =
snapshot.child("children").getValue(List.class);
childrenList[0] = "changedchild1"
snapshot.child("children").setValue(childrenList[0]);
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
}
If you want to remove the child programmatically, simply change this on the code I placed before, inside onDataChange method:
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
snapshot.child("children").removeValue();
}
CodePudding user response:
The property called children
in your database is actually a single string value. To remove the child1
substring from it, you'll have to:
- Read the entire
children
property into your application code. - Modify the string to remove the (first)
child1
. - Write the modified string back to the database.
Alternatively you can do what OneKe answered and turn the children
property into a list (using push()
to generate the keys) or into a map (where child1
and all are keys and they all have a value of true
).