I have implemented Firebase Database
and can successfully add items to it and then display them on a RecyclerView
. I also managed to implement Deletion of a child of a database which is successful BUT I need to restart activity to see changes on my phone's screen. For example: when I press Delete on my list item, it disappears from Database instantly but I need to restart the activity to see the change. Here is my code snippets:
private void attachDatabaseReadListener() {
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
locationCurrent = dataSnapshot.getValue(LocationCurrent.class);
locationCurrent.setRefKey(dataSnapshot.getKey());
mLocationAdapter.add(locationCurrent);
}
@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 believe I should work on onChildRemoved
but have no idea where to start. My main Idea was to repopulate recyclerview
using for loop but locationCurrent object I got from datasnapshot is null.
Any ideas where should I start looking for solution? I have also considered to run addValueEventListener
method on my query but I run into the problem where I get multiple copies of my single child
UPDATE Referring to some comments here is my adapter
public class LocationAdapter extends ArrayAdapter<LocationCurrent> {
public LocationAdapter(Context context, int resource, List<LocationCurrent> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_location, parent, false);
}
LocationCurrent currentLocation = getItem(position);
TextView nameTextView = (TextView) convertView.findViewById(R.id.nameTextView);
TextView descriptionTextView = (TextView) convertView.findViewById(R.id.descriptionTextView);
nameTextView.setText(currentLocation.getName());
descriptionTextView.setText(currentLocation.getDescription());
return convertView;
}
}
By the way - my Ref Key which is used in locationCurrent class is transient variable and thus not visible in Database.
UPDATE2
After all day of working, I still did not manage to get the item off the adapter as soon it is deleted. Instead - I came up with a temporary solution - I added a recreate()
method inside my onChildRemoved
and it does it's job. (Not a good practice but still - something)