Reputation: 87
I have some trouble with removing an item in my Firebase database on click. When I click the button it deletes everything in that database.
The relevant code is below. Any help would be much appreciated!
private static final String FIREBASE_URL = "https://athenajs.firebaseio.com/favourites";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Firebase.setAndroidContext(this);
Intent in = getIntent();
// Get JSON values from previous intent
final String link = in.getStringExtra(KEY_LINK);
firebaseRef = new Firebase(FIREBASE_URL).child("link");
vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
cardView = (CardView) findViewById(R.id.cv);
rv = (RecyclerView) findViewById(R.id.rv);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setTag(1);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final int status = (Integer) view.getTag();
if (status == 1) {
fab.setImageResource(R.drawable.ic_favorite_white_48dp);
Snackbar.make(view, "Added to favourites!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
view.setTag(0);
firebaseRef.push().setValue(link);
} else {
fab.setImageResource(R.drawable.ic_favorite_border_white_48dp);
Snackbar.make(view, "Removed from favourites!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
view.setTag(1);
firebaseRef.removeValue(null);
}
}
});
Upvotes: 0
Views: 4054
Reputation: 11
Remove Item from Firebase Realtime Database in React & Next js
// firstly create a reference for the database which you want to delete
const dbref = ref(db, `Projects/${e.target.value}`)
you can also use UID instead of e.target.value
// use method Remove Item
remove(dbref)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upvotes: -1
Reputation: 2635
When using push() you generate a random node.
To delete it you would need to do this:
firebaseRef.child(pushId).setValue(null);
However, I can't seem to figure out how you want to delete your link since you would be creating a new one every time,, are you trying to remove the last one you created?
Anyway this is how you can save the key and delete that specific item.
final String pushId = firebaseRef.push().getKey();
firebaseRef.child(pushId).setValue(link);
and then use
firebaseRef.child(pushId).setValue(null)
to delete it.
Upvotes: 2