I'm trying to display a fragment inside a recycler view. When you first load the fragment and return the view you get: E/RecyclerView: No adapter attached; skipping layout.
This is because I actually don't have the adapter attached at first. I call the adapter in a function called createFirebaseListener()
that listens for changes to the database and updates the recyclerview in real time. Here's the code:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.groups, container, false)
createFirebaseListener()
setupSendButton(view)
return view
}
private fun createFirebaseListener(){
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val toReturn: ArrayList<Message> = ArrayList();
for(data in dataSnapshot.children){
val messageData = data.getValue<Message>(Message::class.java)
//unwrap
val message = messageData?.let { it } ?: continue
toReturn.add(message)
}
//sort so newest at bottom
toReturn.sortBy { message ->
message.timestamp
}
setupAdapter(toReturn)
}
override fun onCancelled(databaseError: DatabaseError) {
//log error
}
}
mDatabase?.child("Group Chat")?.addValueEventListener(postListener)
}
private fun setupAdapter(data: ArrayList<Message>){
val linearLayoutManager = LinearLayoutManager(context)
mainActivityRecyclerView.layoutManager = linearLayoutManager
mainActivityRecyclerView.adapter = MessageAdapter(data){
Log.d("we.", "got here!")
}
//scroll to bottom
mainActivityRecyclerView.scrollToPosition(data.size - 1)
}
As you can see, in setupAdapter I update the recycler view each time a new message arrives. Since I am not getting the messages as the fragment loads, I get the error above on loading the fragment. But it also crashes the app if I change the orientation to landscape or if I load another fragment and then come back to this fragment: java.lang.IllegalStateException: mainActivityRecyclerView must not be null
.
How should I best handle populating the recyclerview in onCreateView
?