I tried to add groupie adapter to my recycler view as shown in the code below. However when i run my application, i get a compiler error saying my reyclerview cannot be null (because of kotlin null safe feature). I cant figure out why this adapter is not working.
I know the problem is in the line :
recyclerview_newmessage.adapter = adapter
Here’s the full code
class NewMessageActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.title = "Select User" fetchUsers() } private fun fetchUsers() { val ref = FirebaseDatabase.getInstance().getReference("/users") ref.addListenerForSingleValueEvent(object: ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(p0: DataSnapshot) { val adapter = GroupAdapter<ViewHolder>() p0.children.forEach { Log.d("NewMessage", it.toString()) val user = it.getValue(User::class.java) if (user != null) { adapter.add(UserItem(user)) } } recyclerview_newmessage.adapter = adapter } }) } } class UserItem(val user: User): Item<ViewHolder>() { override fun bind(viewHolder: ViewHolder, position: Int) { viewHolder.itemView.username_textview_new_message.text = user.username } override fun getLayout(): Int { return R.layout.user_row_new_message } }
The final result show display the rows in the recycler view with the usernames that are in my firebase database.
Advertisement
Answer
If you define the recycler view
in the xml file then you need to add it.
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.ref_xml_file) . // add this line supportActionBar?.title = "Select User" fetchUsers() }
if not define into the xml file.
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var recyclerview_newmessage = RecyclerView(this) setContentView(recyclerview_newmessage) . // add this line supportActionBar?.title = "Select User" fetchUsers() }