Reputation: 1024
I am new in Android
and I want to get last 5
or 10
messages
from FirebaseDatabase
.I've tried by using this.
ChatInteractor.databaseReference.orderByKey().startAt(10).endAt(20).addListenerForSingleValueEvent((ValueEventListener) ActivityChatView.this);
NullPointerException
as a result.Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.Query com.google.firebase.database.DatabaseReference.orderByKey()' on a null object reference
DatabaseStructure
is thisupdating
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReferenceFromUrl("https://afdbjkaffirebaseio.com/");
Query query=databaseReference.child(Constants.ARG_CHAT_ROOMS).orderByChild("tKyhXXAf6TQnQgKyAf23RJcwhsn1_S5ClzMeWUEXR9evLJO9CBd9ABCH3").limitToLast(2);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Chat chat=snapshot.getValue(Chat.class);
Log.e("163","ACV"+chat.fromEmail);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log
E/163: ACVnull
Upvotes: 1
Views: 4738
Reputation: 933
DatabaseReference messagesReference = FirebaseDatabase.getInstance().getReference().child("chat_rooms").child("tKyhXXAf6TQnQgKyAf23RJcwhsn1_S5ClzMeWUEXR9evLJO9CBd9ABCH3");
Query chatQuery = messagesReference.orderByChild("your key").limitToLast(5);
chatQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
//do what ever required
}
Hope this helps. Please try.
Upvotes: 4
Reputation:
Update your code as shown below:
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
Query query=databaseReference.child(Constants.ARG_CHAT_ROOMS).child("tKyhXXAf6TQnQgKyAf23RJcwhsn1_S5ClzMeWUEXR9evLJO9CBd9ABCH3").orderByChild().limitToLast("Number of last messages you want to show");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Chat chat=snapshot.getValue(Chat.class);
Log.e("163","ACV"+chat.fromEmail);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Upvotes: 4
Reputation: 324
i think u should use Query for this and that could be
@Override
public Query getQuery(DatabaseReference databaseReference) {
// [START recent_posts_query]
// Last 1000 posts, these are automatically the 1000 most recent
// due to sorting by push() keys
Query recentPostsQuery = databaseReference.child("posts")
.limitToLast(number of post you want);
// [END recent_posts_query]
return recentPostsQuery;
}
this will give you post limited by number you given. you can get more info from Firebase official docs or their github repo Firebase link of github of fragment repo
hope this will help.......
Upvotes: 0