I'm relatively new to Firebase Database, having used MySQL up until now. I know that there's no 'associated' data in Firebase as such, but I think I'm still trying to create it, because that's how my mind works! So, it may be that the problem I'm having is because my data is formatted badly - I'd appreciate any pointers.
In my app (using Android Studio), each user can have a number of Boxes. Each Box uses a single colour Palette (it can be the default one, or a user-defined one). A Palette consists of a number of Colours.
Currently, my data is like this:
Boxes
BoxKey1
name: Test Box
paletteKey: paletteKey1
belongsTo: userKey1
BoxKey2
... etc ...
Colours
ColourKey1
name: Red
hexCode: ff0000
ColourKey2
name: Blue
... etc ...
Palettes
PaletteKey1
name: default
colours
ColourKey1: true
ColourKey7: true
... etc ...
PaletteKey2
... etc ...
Users
UserKey1
name: Joe Bloggs
boxes
BoxKey1: true
BoxKey5: true
... etc ...
So, I can retrieve a list of the User's Boxes easily enough, and list all the names. If the User clicks on a name, then the Box with that name is retrieved and displayed. I also need to display the Palette used (the name and the Colours it contains).
In the Activity, I retrieve the Box as follows:
mBox.setKey(boxKey);
mBox.initialiseBox(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mBox = dataSnapshot.getValue(Box.class);
boxName.setText(mBox.getName()); // Show Box name
// AT THIS POINT I HAVE THE BOX DETAILS, BUT I NEED THE PALETTE DETAILS TOO
}
});
In the Box class, initialiseBox looks like this:
public void initialiseBox(ValueEventListener listener) {
if(this.key == null) return;
DatabaseReference mBoxReference = FirebaseDatabase.getInstance().getReference()
.child("boxes").child(this.key);
mBoxReference.addListenerForSingleValueEvent(listener);
}
That's working fine, but at this point I've only retrieved the Palette key from the database along with the other Box data. How do I then get the actual Palette, with all its Colours, so I can show those as well?
I've been trying to do a kind of 'nested listener' like this in the Main Activity:
mBox.initialiseBox(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Same as before
mBox = dataSnapshot.getValue(Box.class);
boxName.setText(mBox.getName()); // Show Box name
// Now add a new listener for the Palette
mPalette.setKey(mBox.getPaletteKey());
mPalette.initialisePalette(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mPalette = dataSnapshot.getValue(Palette.class);
paletteName.setText(mPalette.getName());
}
});
}
});
but it seems very unwieldy, and I can't quite get it to work (the Palette isn't getting populated, so at the paletteName.setText bit I'm getting an error).
Is this the correct approach to be taking? If not, what should I be doing? And if it's the right idea, can anyone see where I'm going wrong?