Wafi_ck
Wafi_ck

Reputation: 1378

The best approach to store list in Firebase Firestore

I want to keep a list with the ID of the users who liked the specific object. To achieve that I created an array where I'm trying to keep that list.

enter image description here

I also want to display how many users like that object.

In mapper:

likes = getLikedListSize(it["userLikedOfferList"].toString())

then

private fun getLikedListSize(userList: String): String {
        return userList.length.toString()
}

The problem is that function returns random numbers. For example in the array are two items, function return "8" etc.

What is a better approach to store list and get the size of it in Firestore?

Upvotes: 0

Views: 407

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

When you are using the following method call:

getLikedListSize(it["userLikedOfferList"].toString())

It means that you are trying to pass to the getLikedListSize() method, the String representation of the array object. This representation is nothing else but the address of the object in the memory. This address it's a String that consists of 8 characters. That's the reason why, when you call .length you return the length of that String and not the actual length of the array. To solve this, simply pass the array, without converting it to a String:

getLikedListSize(it["userLikedOfferList"])

And change the method like this:

private fun getLikedListSize(userList: Array<String>): Int {
    return userList.length
}

Now, when calling this method, you'll always get the number of elements that exist in the userLikedOfferList array.

Upvotes: 1

Related Questions