0

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

Community
  • 1
  • 1
SaltySea
  • 700
  • 1
  • 7
  • 21
  • When I run the code you posted, it behaves as expected. Export and post a slice of your database that shows the structure and timestamp values. – Bob Snyder Dec 23 '16 at 22:33
  • @qbix thank you, I put a picture of my data in the question above under EDIT. – SaltySea Dec 23 '16 at 23:18
  • I suspect reference `mDatabase` is not set correctly. Post the code that defines it. – Bob Snyder Dec 23 '16 at 23:28
  • @qbix private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); as a global variable – SaltySea Dec 23 '16 at 23:47

2 Answers2

1

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);
Bob Snyder
  • 37,759
  • 6
  • 111
  • 158
0

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.

seansanders
  • 95
  • 10