1

I have this data in "Firestore", I want to get all documents according to "city" like all users who have city "karachi" and stored in arrayList of type "chatModel" I want to show this data in recyclerView

Here is the image of dataabase:
Here is the image of dataabase

I have tried this but it's only getting me the last document from collection.

      firestore.collection("USERS")
        .whereEqualTo("city",cityName)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {

                arrayList.add(document.toObject(chatModel::class.java))

                Log.i("Info", "${document.id} => ${document.data}")


            }

            val adapter = chatAdapter(context!!, arrayList)
            chatRecyclerView.layoutManager = LinearLayoutManager(context,
                LinearLayoutManager.VERTICAL,false)
            chatRecyclerView.adapter = adapter
            adapter.notifyDataSetChanged()
        }

Here is the Logcat result:

v21GH5sBi3SdIb3v3xsp3ob64S23 => {username=Muhammad Rizwan, Email=mr1017753@gmail.com, city=Karachi, ProfileImageUrl=https://firebasestorage.googleapis.com/v0/b/me2wee-1b547.appspot.com/o/USERS-MEDIA%2Fv21GH5sBi3SdIb3v3xsp3ob64S23?alt=media&token=193c4013-c580-45dc-b63d-fee1ef13caba}

Here is the screenshot of all documents which contain the city "Karachi" but it's only getting the last one

enter image description here

M--
  • 25,431
  • 8
  • 61
  • 93
Android Geek
  • 23
  • 1
  • 5

2 Answers2

1

The most probable problem with lowercase and upper case. You're problem might be similar to this question

As I can see your described in database city value is karachi in lowercase but output you provided uppercase Result.

firestore.collection("USERS").get()
    .addOnSuccessListener { documents ->
        for (document in documents) {
            if(document.get("city").equals("karachi") || document.get("city").equals("Karachi")){
                arrayList.add(document.toObject(chatModel::class.java));
            }
        }

        val adapter = chatAdapter(context!!, arrayList)
        chatRecyclerView.layoutManager = LinearLayoutManager(context,
            LinearLayoutManager.VERTICAL,false)
        chatRecyclerView.adapter = adapter
        adapter.notifyDataSetChanged()
    }
M--
  • 25,431
  • 8
  • 61
  • 93
Ashish
  • 6,791
  • 3
  • 26
  • 48
0

I have tried this but it's not working

It doesn't work because you are creating a chatAdapter object at every iteration of your for loop. To solve this, move the last four lines of code outside the loop. Inside the loop should exist only:

arrayList.add(document.toObject(chatModel::class.java))

In this way you populate the list and set the adapter only when the list is full of objects.

Ashish
  • 6,791
  • 3
  • 26
  • 48
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193