Reputation: 11276
I have been working on a Firebase backed Android app and this is what my datatbase looks like
{
"Category" : {
"-KhHnKaR2oS0JKNrAQWr" : {
"CategoryDescription" : "Ne est",
"CategoryName" : "New Test Category",
"CategoryThumbnail" : "/New Test Category/New Test Category-thumb.jpg",
"ThumbnailFileType" : "jpg"
}.......
},
"Images" : {
"-KhHBBI4QloAEBDxcUac" : {
"Category" : "-KhBGZnCQ5xhYVbP0dtd",
"-KhBGZnCQ5xhYVbP0dtd":true,
"CategoryName" : "please",
"FileType" : "jpg",
"FileURL" : "/please/NewAddTest.jpg",
"Name" : "NewAddTest"
},
"-KhI1wWJK8YUApa0Iv9q" : {
"Category" : "-KhHnKaR2oS0JKNrAQWr",
"-KhHnKaR2oS0JKNrAQWr":true,
"CategoryName" : "New Test Category",
"FileType" : "jpg",
"FileURL" : "/New Test Category/Test Mem.jpg",
"Name" : "Test Mem"
}.....
}
}
And I was able to get categories by referring the key 'Category' and initially I had Cateogry and Images embedded i.e,
"-Kh8YUXwK0sg3OyoTyAU" : {
"CategoryDescription" : "The legendary evergreen Vadivelu",
"CategoryName" : "Vadivelu",
"CategoryThumbnail" : "/Vadivelu/v2.png",
"Images":{"-KhH5nJjaji2OtOPVeQF" : {
"Category" : "-KhBGZnCQ5xhYVbP0dtd",
"-KhBGZnCQ5xhYVbP0dtd":true,
"FileType" : "jpg",
"FileURL" : "/please/New jpg",
"Name" : "New "
}}
}
It worked out well but in the Firebase docs I read that it is safer to keep data normalized and flattened so then I came up with the latest one at the top. When I try to query like below it returns all objects rather than the desired ones,
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference imageRef = database.getReference("Images");
imageRef.keepSynced(true);
try {
imageRef.child("Images").
orderByChild("Images/Category").equalTo(category.memeCategoryID);
imageRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Returns all objects.
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Also I tried to do this,
imageRef.child(category.CategoryID).equalTo(true);
What I intend to do here is implement by multiple - single relationship and fetch all Images tagged to a category, any help is appreciated. I have seen so many threads and the official Firebase documentation is really confusing and does not help me a bit.
Upvotes: 0
Views: 80
Reputation: 598951
When you call orderBy...
, equalTo
or one of the other methods, Firebase returns a new Query
object. So you'll need to capture that query in a new variable:
Query query = imageRef
.child("Images")
.orderByChild("Images/Category")
.equalTo(category.memeCategoryID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
Upvotes: 1