0

I have a recyclerView where I send data with my adapter but got the error

RecyclerView must not be null

code with my adpater:

class InWaitingFragment : Fragment() {

    private lateinit var adapter: FastItemAdapter<BarterWaitingItem>

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?

    ): View? {

        println("CONTAINER:  " + container)

        val inflate: FrameLayout = inflater.inflate(R.layout.fragment_in_waiting, container, false) as FrameLayout

        adapter = FastItemAdapter<BarterWaitingItem>()

       waitingRecyclerView.layoutManager = LinearLayoutManager(this)

       waitingRecyclerView.adapter = adapter

        val retrofit = Retrofit.Builder()
            .baseUrl("http://10.93.182.95:8888")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val service = retrofit.create(RequestManager::class.java)

        val action  = service.getPending()


        action.enqueue(object: Callback<ArrayList<GetBarterResponse>> {
            override fun onResponse(
                call: Call<ArrayList<GetBarterResponse>>,
                response: Response<ArrayList<GetBarterResponse>>
            ) {
                val allBarter = response.body()
                if(allBarter != null){
                    for (c in allBarter){
                        println("OBJET: ${c.buyer_object.title}")
                    }

                    println("ONRESPONSE En attente: " + response.body().toString())
                }
            }

            override fun onFailure(call: Call<ArrayList<GetBarterResponse>>, t: Throwable) {
                println("ONFAILURE En attente: " + t.toString())
            }
        })

        return inflate
    }


}

got an error to on the this of LinearLayoutManager(this), says:

`require:Context!
 Founds: InWaitingFragment
xrisk
  • 3,790
  • 22
  • 45
Alexis Leleu
  • 3
  • 1
  • 2

2 Answers2

1

You should change LinearLayoutManager(this) to LinearLayoutManager(this.context)

r2rek
  • 2,083
  • 13
  • 16
1

For your LinearLayoutManager, Fragments aren't extending Context so you cant use this as parameters. Instead, use this:

waitingRecyclerView.layoutManager = LinearLayoutManager(context!!)

For the runtime error, "RecyclerView must not be null", it's because you're accessing the properties of the waitingRecyclerView inside the onCreateView callback. The layout hasn't been initialized yet. You can move your initialization of waitingRecyclerView to the 'onViewCreated' callback.

If you must initialize the waitingRecyclerView inside onCreateView you can access the waitingRecyclerView via the object you created when inflating the layout, i.e. inflate:

inflate.waitingRecyclerView.layoutManager = LinearLayoutManager(context!!)
inflate.waitingRecyclerView.adapter = adapter
Obi Weng
  • 26
  • 2