Reputation: 854
I am using recyclerView, each row represents a stock, and its connected to a Firebase accout that has users auth, and everytime a user is created i add him to my Firebase databse (when they sign up my Firebase account), each user has "user_stocks" (child) field and i made a longClickListener which deletes a row in my stock list, problem is that i need to also delete this stock in the users account:
i cant find a way to delete the stock from the Firebase database:
public void deleteFromFirebase(String user_id) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users").child(user_id);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
//No metter what i did, it did not delete from fb
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
Can someone please point me to the right direction? Thanks!
Upvotes: 2
Views: 2164
Reputation: 629
Just place null in that child as a value
FirebaseDatabase.getInstance().getReference("users").child(user_id).setValue(null);
Update
Deleting by value
public void deleteFromFirebase(String user_id,final String stockName) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users").child(user_id).child("user_stocks");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot stock : dataSnapshot.getChildren()) {
if(stock.getValue().equals(stockName))
stock.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
Upvotes: 3