Tzen Szen Toh Tzen Szen Toh - 3 months ago 41
Android Question

Remove Single Item in Firebase

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);
}


}

});

Answer

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.

Comments