2 回答
TA贡献1772条经验 获得超5个赞
要解决这个问题,请使用以下方法来检查用户是否看过一本书:
private void checkBookTitle(String bookTitle) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Users").child(uid).child("books_viewed");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue().equals(bookTitle)) {
Log.d(TAG, "User has viewed this book");
} else {
Log.d(TAG, "User has not viewed this book");
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
}
TA贡献1862条经验 获得超7个赞
首先,books_viewed变成一个数组。阅读本文以了解Firebase 实时数据库中的数组
现在它是一个数组,你可以ArrayList<String>在你的应用程序中获取它。
public class User {
public ArrayList<String> booksViewed;
... // Other variables
}
然后只需使用该contains功能检查您需要查找的书是否在该列表中
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("Users").child("<UserID>")
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
String bookTitleYouAreChecking = "Twilight"
if (user.booksViewed.contains(bookTitleYouAreChecking)) {
// User has viewed
} else {
// User has not viewed
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// ...
}
})
添加回答
举报