1

I am trying to delete a child from the database by setting the unique Key to null. What I do is - I press and hold on a List Item to get the Alert Dialog and then press to delete the entry I have selected. The problem is when I retrieve the key it returns me all the keys. And closest I managed to get so far was to delete everything from the database. Please check my code snapshots below:

 mLocationListView.setLongClickable(true);
    mLocationListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Delete a Location")
                    .setMessage("Do you want to delete your location?")
                    .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

//Problem is here. if I exclude .child(pushKey)everything is deleted from the database. 
                                DatabaseReference db_node = FirebaseDatabase.getInstance().getReference().getRoot().child("locations").child(pushKey);

                        db_node.setValue(null);
                        }
                    });
                AlertDialog alert = builder.create();
                alert.show();
            return true;
        }
    });

Here is how I retrieve pushKey. Any suggestions how to do it in more proper way? (if there is one)

 queryRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            locationCurrent = dataSnapshot.getValue(LocationCurrent.class);
            mLocationAdapter.add(locationCurrent);
            pushKey = dataSnapshot.getKey();
            Log.i("PUSH KEY ", pushKey);

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            locationCurrent = dataSnapshot.getValue(LocationCurrent.class);


        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I was thinking of putting the Key to the database as well but there is no point and there must be the most efficient solution.

UPDATE:

I have tried doing this with another method attaching a single value event listener to the query but it does not work because I cannot determine which list item I click on so I delete the whole database. Basically, I need to click on a list item and delete it. But It does not work. I did exactly as in the link here below:

How to delete from firebase realtime database?

Any suggestions?

Community
  • 1
  • 1
  • 1
    Since the user clicked on a specific item, you need to look up the item at that position. This is part of the adapter's function. It's not clear how to do that in your code, but if you're [using a `FirebaseListAdapter`](https://github.com/firebase/FirebaseUI-Android/tree/master/database#create-custom-firebaselistadapter-subclass) it would be `adapter.getRef(position).removeValue()`. – Frank van Puffelen Dec 24 '16 at 14:47
  • I am using a custom Adapter. So I guess it is better to change it toFirebase List Adapter just for the sake of saving myself from more headache? –  Dec 24 '16 at 14:57
  • 2
    You can stick to a custom adapter. But you will need similar logic that allow you to look up a `DatabaseReference` for an item at the position that was clicked. – Frank van Puffelen Dec 24 '16 at 14:59
  • Thanks. But I guess then I have to create a getter for getting a Key? Since the list item is a locationCurrent type. –  Dec 24 '16 at 15:03
  • Possible duplicate of [How to delete from firebase realtime database?](http://stackoverflow.com/questions/37390864/how-to-delete-from-firebase-realtime-database) – Reaz Murshed Dec 26 '16 at 02:15
  • I had already tried to solve my problem with answers from these questions but it didn't work –  Dec 26 '16 at 13:11

1 Answers1

2

Add a transient variable called refKey in your LocationCurrent.class. Save the ref in onChildAdded

public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    locationCurrent = dataSnapshot.getValue(LocationCurrent.class);
    locationCurrent.setRefKey(dataSnapshot.getKey()); 
    mLocationAdapter.add(locationCurrent);
}

And on delete click do this :

mLocationListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    DatabaseReference db_node = FirebaseDatabase.getInstance().getReference().child("locations").child(mLocationAdapter.getItem(position).getRefKey());
    db_node.removeValue();
});
Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37
  • Thanks! I will give it a go. It looks promising :) –  Dec 25 '16 at 12:17
  • Mark it as correct ! if this has solved your problem :) – Saurabh Padwekar Dec 25 '16 at 16:16
  • I have just started it, so basically I have to save a ref key as a child of the same ref key (Like database entry) –  Dec 26 '16 at 13:31
  • Ok, so I did exactly what you told. I added a transient refKey variable in my LocationCurrent Class (set getters and setter). And then Everything you told above. Now I get an error –  Dec 26 '16 at 15:02
  • java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1 and I have no Idea where to star debugging it –  Dec 26 '16 at 15:03
  • On the 1st line in the onClick method –  Dec 26 '16 at 15:25
  • can you check the value of which(position) ? – Saurabh Padwekar Dec 26 '16 at 15:32
  • I get the same exception. Here are my code changes. LocationCurrent: `private transient String refKey; public String setRefKey(String refKey) { this.refKey = refKey; return refKey; } public String getRefKey() { return refKey; }` And everything else is as above. –  Dec 26 '16 at 15:45
  • i got the problem instead of which put position here , `mLocationAdapter.getItem(position).getRefKey()` – Saurabh Padwekar Dec 26 '16 at 17:48
  • Where exactly is the problem? –  Dec 26 '16 at 17:53
  • check the updated answer , we were taking wrong position , – Saurabh Padwekar Dec 26 '16 at 17:57
  • Thank you very much. I should have paid more attention :) This has solved my problems –  Dec 26 '16 at 20:05