-1

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?

Jeff McBride
  • 73
  • 12
  • The point is, where did you initialized the `mainActivityRecyclerView` ? I can't see it in your codes.. – ʍѳђઽ૯ท Aug 26 '18 at 20:00
  • It is initialized in `import com.ntx_deisgns.cyberchatter.cyberchatter.R`. The name `mainActivityRecyclerView` is the id of my recyclerview. – Jeff McBride Aug 26 '18 at 20:05

1 Answers1

0

It is initialized in import com.ntx_deisgns.cyberchatter.cyberchatter.R. The name mainActivityRecyclerView is the id of my recyclerview

I believe it's not working because you are not initializing the RecyclerView inside the Fragment and it shows must not be null error. So, i'd suggest doing something like this:

  1. Initializing & moving setupAdapter method's codes inside the Fragment after inflating view and before return view.
  2. Override onActivityCreated and moving setupAdapter method's codes inside it and then it should work.

Take a look: Android with Kotlin error when use RecyclerView in Fragment

P.s: Remember, use notifyDataSetChanged() after updating or setting data to an adapter to avoid such errors.

ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
  • Moving `setupAdapter` to `onActivityCreated` gets rid of the `E/RecyclerView: No adapter attached; skipping layout.` error, but if the phone gets rotated to landscape, I get `mainActivityRecyclerView must not be null`. – Jeff McBride Aug 26 '18 at 22:27
  • I need to get the array from `createFirebaseListener` to 'onActivityCreated'. I can't just declare an empty array as that makes it null. – Jeff McBride Aug 26 '18 at 22:36
  • Any ideas on how to get the array into `onActivityLoad` or `onActivityCreated`? – Jeff McBride Aug 27 '18 at 14:34
  • I'd suggest using my answer (First option) first. Also, you don't have to make it too hard for yourself, you can use those codes inside `onCreateView`. About declaring, i think you'll be able to declare a private array in above of `onCreateView` then you can get access to it in the current `Fragment` - `Activity` which is an another issue and not related to this question-thread. Please use ask question for further questions. – ʍѳђઽ૯ท Aug 27 '18 at 15:42
  • Moving `setupAdapter` to `onCreateView` doesn't load the array into the `recyclerView` when entering the fragment though as there is no data inside `setupAdapter`. That data is read from the `onDataChanged` method and that method is never accessed from `setupAdapter`. I need to get the data from `onDataChanged` into the `onCreate`. – Jeff McBride Aug 27 '18 at 15:54
  • Just to be clear, the error I'm getting is `mainActivityRecyclerView must not be null`, but ONLY when the device is rotated to landscape. In portrait mode, everything works just fine. – Jeff McBride Aug 27 '18 at 16:19