Skip to content Skip to sidebar Skip to footer

Android Studio Remove Items From Both Listview And Firebase

I'm trying to remove items from both listview and firebase in android studio. When I remove items from the firebase console, it automatically removes items from listview. However I

Solution 1:

To solve this, use the following lines of code:

listView.setOnItemClickListener(newAdapterView.OnItemClickListener() {
    @OverridepublicvoidonItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Stringitem= adapter.getItem(position);
        adapter.remove(item);
        adapter.notifyDataSetChanged();
        //Delete item form Firebase database
    }
});

I have added a setOnItemClickListener on your listView and remove the item from the adapter first and them from your database accordingly to the item that was clicked.

Solution 2:

Now this solution might be hard coded, but that's because you're only storing Strings on the database while you also need their keys to tell firebase which one to delete. My recommendation is having a second ArrayList to store the keys and access it on Item Click.

So first you declare this ArrayList, let's name it keysList:

private ArrayList<String> arrayList = new ArrayList<>();
private ArrayList<String> keysList = new ArrayList<>();

then you must change your onChildAdded method to store those keys in the ArrayList:

@OverridepublicvoidonChildAdded(DataSnapshot dataSnapshot, String s) {
            Stringstring = dataSnapshot.getValue(String.class);

            arrayList.add(string);
            keysList.add(dataSnapshot.getKey());

            adapter.notifyDataSetChanged();
        }

But then you'd also have to change your onChildRemoved to remove the deleted keys from the keysList:

@OverridepublicvoidonChildRemoved(DataSnapshot dataSnapshot) {
            Stringstring = dataSnapshot.getValue(String.class);

            arrayList.remove(string);
            keysList.remove(dataSnapshot.getKey());

            adapter.notifyDataSetChanged();
        }

And finally, add an onItemClickListener to your listView so that the user can click to remove the item from Firebase:

listView.setOnItemClickListener(newAdapterView.OnItemClickListener() {
            @OverridepublicvoidonItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Stringkey= keysList.get(position);
                mDatabase.child(key).removeValue();
            }
        });

Post a Comment for "Android Studio Remove Items From Both Listview And Firebase"