Java – how to delete firebase data after “n” days

I want to delete some old data in my friedbase I know this question has been asked a lot here, but it is still difficult for me to make it work

I'll try the solution found here:

Firebase chat – removing old messages

But this has been abandoned

So let me try this:

ChildEventListener childEventListener = new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot,String s) {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-30);


        Log.d(TAG,"onChildAdded:" + dataSnapshot.getKey());

        String key = dataSnapshot.getKey();

        Marker retrievemarker =dataSnapshot.getValue(Marker.class);
        Calendar t3 = new           
        GregorianCalendar
        (c.get(Calendar.YEAR),c.get(Calendar.MONTH),retrievemarker.getSavedate());

        int date1= calendar.get(Calendar.DATE);
        int date2= t3.get(Calendar.DATE);

        Log.d("date1",""+date1);
        Log.d("date2",""+date2);

        if( date1 == date2 ){

            myRef.child(key).setValue(null);

        }

Explanation: in my firebase, I saved an object named marker, which obtained a variable to store the saved object, that is, the date on which the object was saved in firebase

int date = c.get(Calendar.DATE);
marker.setSavedate(date);

I hope to delete the objects in firebase in 30 days Therefore, I try to subtract 30 days from today's date instead of comparing it with the saved item from the object. If it equals, I will delete the object from firebase

For synthesis, I refer to the following answers:

How to subtract X days from a date using Java calendar?

But it doesn't work If I add an object to firebase today, the two dates will always be equal So I guess subtraction doesn't work

What on earth did I do wrong?

Solution

Suppose you have a data structure with nodes:

-KItqNxLqzQoLnUCb9sJaddclose
  time: "Thu Apr 28 17:12:05 PDT 2016"
  timestamp: 1461888725444

Each such node has a timestamp attribute indicating when it was created You'd better set this property to using server timestamp

Using this data structure, you can easily build queries that return only items older than 30 days and delete them:

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

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>