SaltySea
SaltySea

Reputation: 740

Deleting Firebase data after a certain time

I've been trying to make this work from

How to delete firebase data after "n" days

but it's not working for me.

Here's what I'm doing,

In my "A" activity, I have a button that will save this chunk of data, with a 'timeStamp' child which holds the timestamp value. (.setValue(ServerValue.TIMESTAMP);)

After pressing the button, it saves the data successfully. Then, it starts the next activity, where we wait.

But instead of deleting after '30' days, it deletes it straight away.

I have a method that works exactly like the answer by Frank

long cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS);
    Query oldBug = mDatabase.orderByChild("timeStamp").endAt(cutoff);
    oldBug.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot itemSnapshot: snapshot.getChildren()) {
                itemSnapshot.getRef().removeValue();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

But it's not deleting it after some time, as soon as it is posted.

Thank you.

EDIT:

data

Upvotes: 0

Views: 4087

Answers (2)

Bob Snyder
Bob Snyder

Reputation: 38289

The orderByChild() sorting method is very forgiving. The children being sorted are not required to have a member with the specified field name. The documentation explains that those children are assigned a null value and appear first in the sort. Thus, if the reference used to create a query is incorrectly located, the query doesn't fail and instead will typically return all the children of that location.

You created your oldBug query using mDatabase where:

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

This is one level too high. It should be:

 Query oldBug = mDatabase.child("Users").orderByChild("timeStamp").endAt(cutoff);

Upvotes: 1

seansanders
seansanders

Reputation: 95

I think you might consider making a new child item that has a timestamp and date so that you can reference back to it when doing a query for the date and time. This way you don't have to worry about incorrect values and you can ensure you are deleting the correct data. I hope this helps.

Upvotes: 0

Related Questions