Rahul
Rahul

Reputation: 3349

endAt() with limitToLast() in Firebase query is not working as expected in android

I am using the firebase real-time database to store chat messages schema is like below

"chat_message" : {
    "up-29709425-fef2-490c-8335-77dbeafbce1e" : {
      "-MLhPH_i7bfvnTpccK1k" : {
        "chat_room_id" : "up-29709425-fef2-490c-8335-77dbeafbce1e",
        "created_at" : "2020-11-09T19:59:11+05:30",
        "creator_id" : 15456623,
        "message" : "hii",
        "message_type" : "text",
        "time_in_ms" : 1604932151865
      }
    },
    "up-299bcd2f-90bb-4ca2-b526-7e858d2d98fe" : {
      "-MLhWydTKmB52W_XFtS6" : {
        "chat_room_id" : "up-299bcd2f-90bb-4ca2-b526-7e858d2d98fe",
        "created_at" : "2020-11-09T20:32:47+05:30",
        "creator_id" : 15451746,
        "message" : "hoi",
        "message_type" : "text",
        "time_in_ms" : 1604934167159
      }
    }

The problem is for the first time, I am getting 10 items and after that, I am not able to get the next 10 items. Here are the queries I am using

 private var query: Query? = null
private fun getInitialChatMessages(time: String?, key: String?) {
        query = if (time == null) {
            // For first time I am getting last 10 items 
              getFirebaseDbReference()
                .child(FIREBASE_DATABASE_LOCATION_MESSAGES)
                .child(project?.userProjectId!!)
                .orderByChild("time_in_ms")
                .limitToLast(INITIAL_FETCH_MESSAGE_COUNT)
        } else {
          // on scroll its not working   
            getFirebaseDbReference()
                .child(FIREBASE_DATABASE_LOCATION_MESSAGES)
                .child(project?.userProjectId!!)
                .orderByChild("time_in_ms")
                .endAt("$time")
                .limitToLast(INITIAL_FETCH_MESSAGE_COUNT)
        }

        query?.addListenerForSingleValueEvent(listener)
    }

Any help would be appreciated. Thanks in advance.

Upvotes: 0

Views: 207

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

The time property in your database is a numeric value, but in your code you're passing it as a string. When the database compares a number and a string, they are never the same.

So you'll want to fix your code so that is also treats the time as a number, or at the very least pass is as a number to the database by calling toDouble() on it.

Upvotes: 1

Related Questions