Delete a set of firebase data automatically after

2019-04-16 17:19发布

问题:

I have some data in FirebaseDatabase in which every data set has two properties: startTime and endTime.

Here's the data-structure:

app
 -ref
   -uniqueID1
     -key: value
     -startTime: 1488849333
     -endTime: 1488853842
     -key: value
   -uniqueID2
     -key: value
     -startTime: 1488850198
     -endTime: 1488853802
     -key: value

What I want is to deleted the data set when the endTime has passed automatically or when the user opens the app.

I have done some research on this topic and found this, but this doesn't seems helpful to me.

How can I remove the datasets whose endTime has passed?

回答1:

This looks like a similar answere but you seem not to understand the answer. So here is how to do it. Since what matters is the end time only we are going to monitor when it has passed. To do this, we get the current time

Date().getTime();

and check whether its greater than the end time(if it is, it means that the end time has passed)

final DatabaseReference currentRef = adapter.getRef(position);
                    currentRef.child("endTime").addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            long time = System.currentTimeMillis();  //get time in millis
                            long end = Long.parseLong( dataSnapshot.getValue().toString()); //get the end time from firebase database

                            //convert to int
                            int timenow = (int) time; 
                            int endtime = (int) end;

                            //check if the endtime has been reached
                            if (end < time){
                                currentRef.removeValue();  //remove the entry
                            }
                        }
                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

i have implemented that code when the item i want to remove is clicked. so the adapter is from a listview. Thanks, i hope it helps