'Firestore returns empty list [duplicate]

I have 3 entries in my firestore database. I need to query the data and fetch it, then input it into an ArrayList. The problem is my query is always returning empty hence the list does not get populated. I have tried pointer debugging this but to no avail. The following is the code in my .kt file

class Users : AppCompatActivity() {

    private val db = Firebase.firestore
    private lateinit var recyclerView: RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_users)


        val userList = ArrayList<User>()
        db.collection("Users").get()
            .addOnCompleteListener(OnCompleteListener<QuerySnapshot?> { task ->
                if (task.isSuccessful) {
                    for (document in task.result) {
                        val user = User(document.data["name"] as String, document.data["email"] as String)
                        userList.add(user)
                    }
                    Log.d(TAG, userList.toString())
                } else {
                    Log.d(TAG, "Error getting documents: ", task.exception)
                }
            })

        recyclerView = findViewById<RecyclerView>(R.id.rv)
        val adapter = UsersAdapter(userList)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)





    }
}


Solution 1:[1]

First of all, what if Firebase.firestore? Are you checking if that variable is returning an app or an instance? Or, you just debug it using for example: Log.e("TAG", "$db") or using the Android debugger.

To debug inside of the lambda I recommend you to use the following code:

db.collection("Users").get()
        .addOnCompleteListener(object : OnCompleteListener<QuerySnapshot?> {
            override fun onComplete(task: Task<QuerySnapshot?>) {
                if (task.isSuccessful) {
                    for (document in task.result!!) {
                        val user = User(document.data["name"] as String, document.data["email"] as String)
                        userList.add(user)
                    }
                    Log.d(TAG, userList.toString())
                } else {
                    Log.d(TAG, "Error getting documents: ", task.exception)
                }
            }
        })

In that block you can use the Android Debugger because it's not a lambda function, so, when you figured out the null data and fixed it you can switch the object function to a lambda.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jorge Aldana