I am trying to delete old messages into a FriendlyChat using timestamp. I am using this post How to delete firebase data after "n" days to try to solve. The problem i have: This code to my firebase database is deleting all messages not only the messages I need.
My firebase database JSON:
{
"messages" : {
"Bl0AiMMUXsV2H58lqoj0rO84" : {
"-KYo1YqO9vQ4Fcc07TcU" : {
"dateCreatedGu" : {
"date" : 1481563061846
},
"name" : "nameOfUser",
"photoUrl" : "https://lh6.g/photo.jpg",
"text" : "h"
},
"-KYo1atRyY3VYxuTZRPZ" : {
"dateCreatedGu" : {
"date" : 1481563074335
},
"name" : "\"nameOfUser\"\"",
"photoUrl" : "https://lh6.googleusercontent.com.../-photo.jpg",
"text" : "g"
},
"-KYo1bQXtJNB94et25m2" : {
"dateCreatedGu" : {
"date" : 1481563076516
},
"name" : "Gus",
"photoUrl" : "https://lh6.../photo.jpg",
"text" : "b"
},
"-KYo4GmLdM0TyT_Aym0u" : {
"dateCreatedGu" : {
"date" : 1481563774514
},
"name" : "gus",
"photoUrl" : "https://lh6.go.../photo.jpg",
"text" : "h"
}
}
}
}
My snippet code Android :
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference("messages");
//beginn n-days
long cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS);
Query oldItems = mFirebaseDatabaseReference.orderByChild("timestamp").endAt(cutoff);
//
oldItems.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot itemSnapshot: snapshot.getChildren()) {
itemSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//end n-days
The difference here is my timestamp into date is into "dateCreatedGu and not on the message directly because I used Map to store the timestamp .
What is wrong? How can I correctly delete only the messages I need - the messages older than 30 days for example?
I tried to change the period form 30 days to 30 seconds into cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS);
to verify the code.
I tried to change from addValueEventListener
to add ChildEventListener...
i understood that orderByValue
is used when you are not reading an object with attributes but reading directly the attribute.
I understood that in this case it is better to optimize the code using orderbyKey because the key are stored in the alphabetical order during time - jumping values) - usefull to optimeze the search of timestamp that increasing too.
I understood that addChildEventListener
tries to read each value inside your database f exist more than one message (for example).
But i still not found how to delete only the messages I need.
How can i do it with my database?