Reputation: 181
I have two models photos and videos. To retrieve photos I call an addChildEventListener and to get videos I call another addChildEventListener added.
Code example
databaseReference = FirebaseDatabase.getInstance().getReference("videos");
Query queryContent= databaseReference;
queryContent.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
videos v= dataSnapshot.getValue(videos.class);
objectItems.add(v);
loading = true;
contentViewPager.setAdapter(new discover_fullscreen_adapter(getApplicationContext(), objectItems));
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
For photos is the same, I just change the reference, and the model
databaseReference = FirebaseDatabase.getInstance().getReference("photos");
photos p = dataSnapshot.getValue(photos.class);
objectItems.add(p)
First I add the videos and then the photos and the order is messy because I want to get videos and photos together in the order they were taken. Like a phone gallery. We have photos and videos ordered in the way they were taken (timestamp in his case). How can I achieve the same knowing that photos and videos are in different nodes and they are called by different models? How to do it with Firebase Realtime Database
My models are based on getter and setter, I don't want to make the question bigger.
Thank you
Upvotes: 1
Views: 390
Reputation: 139019
I want to get videos and photos together in the order they were taken. Like a phone gallery.
You can perform a Firebase Realtime Database query only on a single node. You cannot get data across multiple nodes using a Query. If you want to get the "photos", as well as the "videos" in a single go, then both should exist within the same node. So you should create another node called "photosAndVideos" where you should add all the data. This practice is called denormalization and is a common practice when it comes to Firebase. For a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database.
Once you have all data under a single node, you can then perform the desired query according to a timestamp. Please see my answer from the following post:
To see how to add a timestamp property to your object. By default Firebase orders the results ascending. However, if you need a descending order, please see my answer from the following post:
Edit:
You have to check each object from the results an instance of which class is. So when you read the data, you cannot only cast the value. You'll have to read each object and request the correct class in the call to getValue().
Upvotes: 1