I am new to Firebase and I am facing a problem in delete an item from the recycler view I created. but I am unable to understand how to delete items using an auto-generated key. This is how I added item into the database :
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("categories");
String key = reference.push().getKey();
reference.child(key).setValue(categoryData).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(add_category.this, "Category added", Toast.LENGTH_SHORT).show();
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(add_category.this, "Failed to add", Toast.LENGTH_SHORT).show();
}
});
As in your comment, if you want to delete, for example, the second item, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference secondChildRef = rootRef.child("categories").child("-M1qUEGi0u4rX5Ju59r4");
secondChildRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "Second item deleted!");
}
}
});
So to delete a particular item, you to know its ID so you can add it to the reference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.