Reputation: 24472
I have a node that stores a list of project keys for each user.
The structure of my user_projectes
is:
I have started to play with Firebase for Android and I ended up with this:
mFirebaseDatabaseReference.child("user_projects").child(mFirebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot projectSnapshot: snapshot.getChildren()) {
Log.e("Project","Project Key found: " + projectSnapshot.getKey());
}
}
@Override
public void onCancelled(DatabaseError firebaseError) {
Log.e("Chat", "The read failed: " + firebaseError.getDetails());
}
});
Currently what I got are keys for the projects.
I have another node, projects
, which stores the project data.
The projects data are stored in my projects/$projectKey
node.
I will also have to populate the project name
and photoURL
inside my ListView/GridView.
How I can retrieve the project data for each project key I got and add it to my listview?
Upvotes: 1
Views: 625
Reputation: 10350
Unfortunately, as @rhari mentions, you do have to make another query....what I've found useful when doing "joins' like this with firebase is to use RxJava...could have something like following for example (which you could use then in your adapter to populate ListView/RecyclerView)
public Observable<Project> getProjects(String userId) {
return getProjectKeys(userId).flatMap(projectKey -> getProject(projectKey));
}
Where this falls down is where you want your list to dynamically update as projects are added....in that case you'll need version of listner that has onChildAdded
/onChildRemoved
etc and will need then to do lookup of project from those.
Upvotes: 2
Reputation: 1367
Just query the database again
mFirebaseDatabaseReference.child("user_projects").child(mFirebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot projectSnapshot: snapshot.getChildren()) {
String key = projectSnapshot.getKey();
mFirebaseDatabaseReference.child("projects").child(key)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot1) {
Project p = snapshot1.getValue();
}
}
}
@Override
public void onCancelled(DatabaseError firebaseError) {
Log.e("Chat", "The read failed: " + firebaseError.getDetails());
}
});
Upvotes: 2
Reputation: 5339
You have to create a model for your project entity then you can use Project mProject = projectSnapshot.getValue(Project.class);
Upvotes: 0