0

Hello I am trying to implement a RecyclerView of users that are in my RealtimeDatabase, but this code dosen't work and I dont know why. Here is the code for Activity.

class NewMessageActivity : AppCompatActivity() {
    private val TAG = "NewMessageActivityTag/////////////////////////////"
    private lateinit var binding : ActivityNewMessageBinding
    private lateinit var realtimeDatabase : FirebaseDatabase
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityNewMessageBinding.inflate(layoutInflater)
        setContentView(binding.root)

        supportActionBar?.title = "New Message"
        realtimeDatabase = FirebaseDatabase.getInstance("https://firechat-931d2-default-rtdb.asia-southeast1.firebasedatabase.app/")
        val users = fetchUsers()
        Log.d(TAG,"vkgjhbiuglkjhglioiuhghubgDone2 $users")
        binding.rvNewMessageActivity.adapter = UsersAdpater(this,users)
        binding.rvNewMessageActivity.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)

    }

    private fun fetchUsers() : ArrayList<UserInfo> {

        val ref = realtimeDatabase.getReference("/users")
        val userList = ArrayList<UserInfo>()
        Log.d(TAG,"pidsnigfngadsnfpoin")
        ref.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if(snapshot.exists()) {
                    Log.d(TAG,"$snapshot")
                    for(child in snapshot.children){
                        val tempchild = child.getValue(UserInfo::class.java)
                        Log.d(TAG,"$tempchild")
                        userList.add(tempchild ?: UserInfo("default_UID","default_email","default_name","default_picurl"))
                    }
                }
            }

            override fun onCancelled(error: DatabaseError) {
                Log.d(TAG,"$error ${error.message}")
            }

        })
        Log.d(TAG,"$userList")
//        if(userList.isEmpty()) {
//            for(i in 1..10) {
//                userList.add(UserInfo("default_UID$i","default_email$i","default_name$i","https://firebasestorage.googleapis.com/v0/b/firechat-931d2.appspot.com/o/ProfileImages%2FL5yOgELQtmXdUcnxf7S6Iqs1OsN2.profileImage?alt=media&token=3573195b-a5bb-499f-a79b-7191d5ad2655"))
//            }
//        }
        return userList

    }
}

Now I'll add the data class code 1

Now I'll add the adapter

class UsersAdpater(val context : Context, val gotData : ArrayList<UserInfo>) : RecyclerView.Adapter<UsersAdpater.UserViewHolder>() {

    private var data : ArrayList<UserInfo> = gotData

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user_newmessasgesactivity,parent,false)
        return UserViewHolder(view)
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        holder.username.text = data[position].name
        holder.useremail.text = data[position].email
        Glide.with(context).load(data[position].profilePicUrl).into(holder.userImage).onLoadFailed(ContextCompat.getDrawable(context,R.drawable.profilepicnormall))
        holder.entireLayout.setOnClickListener {
            //TODO("IMPLEMENT OPENING A NEW CHAT WITH THIS USER")
            Log.d("NewMessagesActivity","${data[position].toString()}")
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    private fun updateList(userList : ArrayList<UserInfo>) {
        data = userList
    }

    inner class UserViewHolder(private val itemView : View) : RecyclerView.ViewHolder(itemView) {
        val username = itemView.findViewById<TextView>(R.id.item_rvnma_username)
        val useremail = itemView.findViewById<TextView>(R.id.item_rvnma_email)
        val userImage = itemView.findViewById<ImageView>(R.id.item_rvnma_image)
        val entireLayout = itemView
    }
}

// In the Log 2 As you can see the the function fetchUsers() has already returned an empty list and the data is logged after that. Why so ? And also why is it returning an empty list when it logs data for every user?

Is it because the fetching of users takes time? Do I need to use Coroutines?

  • 1
    There is no way you can return that `userList` as a result of a method. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this article, [How to read data from Firebase Realtime Database using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Nov 17 '21 at 11:08
  • Also @AlexMamo can you please attach some links for me to know more about async stuff. Also can it be used with coroutine? If yes. Please attach the Link. – Brahat Singh Nov 17 '21 at 17:47
  • Yes, it can. Please check the corresponding [repo](https://github.com/alexmamo/RealtimeDatabase). – Alex Mamo Nov 18 '21 at 07:43

0 Answers0