Reputation: 77
I am having trouble getting data from my database.
My code:
Query query = FirebaseDatabase.getInstance().getReference("Quotes").startAt(5).endAt(10);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String authorName = data.child("Name").getValue().toString();
String quoteGiven = data.child("Quote").getValue().toString();
name.setText("- " + authorName);
quote.setText(quoteGiven);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "Loading Quote failed", Toast.LENGTH_SHORT).show();
}
});
I want to get my data from the 5th child to the 10th child.
I've tried:
Select random entry from Firebase Realtime Database in Java
get random value android firebase java
Firebase queries not working on Android even though the reference retrieves data
However, the is only showing the hard-coded text I left and not the text from the database?
can anyone help me, I am not sure where i went wrong
Upvotes: 1
Views: 623
Reputation: 80914
Try using orderByKey()
:
FirebaseDatabase.getInstance().getReference("Quotes").orderByKey().startAt(String.valueOf(5)).endAt(String.valueOf(10));
This should give you all the data from the 5th key to the 10th in your database.
From the docs:
orderByKey()
Order results by child keys
https://firebase.google.com/docs/database/android/lists-of-data#sort_data
Upvotes: 3
Reputation: 138824
To solve this, please change the following line of code:
Query query = FirebaseDatabase.getInstance().getReference("Quotes").startAt(5).endAt(10);
to
Query query = FirebaseDatabase.getInstance().getReference("Quotes")
.orderByKey().startAt("5").endAt("10");
The keys that you pass to the startAt()
and endAt()
methods, should always be strings and not numbers.
Upvotes: 2