[英]Firebase Deleting A Value
I'm developing an app with Android Studio using Firebase.我正在使用 Firebase 使用 Android Studio 开发应用程序。 I want to delete a certain date but when I click on the delete button it does nothing.
我想删除某个日期,但是当我单击删除按钮时,它什么也不做。 I can't reach to parent because it's a generated key.
我无法联系到父母,因为它是生成的密钥。 Any help would be appreciated.
任何帮助,将不胜感激。
private void deleteDate(){
String dateValue = showDate.getText().toString();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userid = user.getUid();
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("smokeFreeDays");
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
for (DataSnapshot userDataSnapshot : snapshot.getChildren()) {
String date = userDataSnapshot.getValue(String.class);
if (date.equals(dateValue)) {
snapshot.getRef().child(dateValue).removeValue();
} else if (!date.equals(dateValue)) {
snapshot.getRef().child(dateValue).removeValue();
}
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
Log.w("tag", "loadPost:onCancelled", error.toException());
}
});
}
My Database:我的数据库:
See my comment above for debugging the issue.请参阅我上面的评论以调试问题。
But as an overall hint, I'd recommend reconsidering the data structure under smokeFreeDays
to look like this:但作为一个整体提示,我建议重新考虑
smokeFreeDays
下的数据结构,使其看起来像这样:
"smokeFreeDays": {
"2021-05-09": true,
"2021-05-10": true
}
The two changes in this structure:这种结构的两个变化:
year-month-day
, which is better suited for querying.year-month-day
,更适合查询。 For example, you can get all smoke free days in 2021 with: usersRef.orderByKey().startAt("2021-").endAt("2021~")
.usersRef.orderByKey().startAt("2021-").endAt("2021~")
获得 2021 年的所有无烟日。smokeFreeDays
to find the value to delete.smokeFreeDays
来查找要删除的值。 You can now delete the node once you know the date with: usersRef.child("2021-05-09").removeValue()
.usersRef.child("2021-05-09").removeValue()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.