"Posts" : {
"-MnLFAlhayTv80FxzUfL" : {
"description" : "",
"picture" : "",
"postKey" : "-M",
"timeStamp" : 1635682139495,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
"-MnLFzItc050Sn0EtDho" : {
"description" : "",
"picture" : "",
"postKey" : "-M",
"timeStamp" : 1635682350531,
"title" : "",
"userId" : "b",
"userPhoto" : ""
},
This is my data structure. I'm going to make a code that delete old post by using orderbyChild(timeStamp).endAt() method when I experiment with just long variable like 1635682350531 this ->> orderbyChild(timeStamp).endAt(1635682350531l); It works when I add l to 1635682350531
And I define the current timestamp variable and put this to endAt method but It doesn't work. I may think I didn't add "l" to my variable?
Here is my code.
if (UId.equals("k")) {
long tlong = System.currentTimeMillis(); long ttime;
ttime = tlong - 3*24*60*60*1000;
StorageReference picRef = FirebaseStorage.getInstance().getReferenceFromUrl(postImage);
showMessage(String.valueOf(ttime));
picRef.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//image deleted, now delete database
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").endAt(ttime);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되지않았습니다.",Toast.LENGTH_SHORT).show();
}
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed, can't go further
Toast.makeText(PostDetailActivity.this, "" e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Thank you for answering me.
CodePudding user response:
When you are using the following query:
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").endAt(ttime);
There is an index required. So most likely the following log statement:
Log.d("TAG", task.getException().getMessage());
Produces the following error message:
Index not defined, add ".indexOn": "timeStamp", for path "/Posts", to the rules
To solve this, you have to set the following rules:
{
"rules": {
"Posts": {
".indexOn": "timeStamp",
".read": true,
".write": true
}
}
}
In order to make it work. Having this index in place, your query will return the expected results and the following line of code:
ds.getRef().removeValue();
Will remove both children from the database.