我该如何修复错误 'java.lang.IllegalStateException: RecyclerView must not be null'

How can i fix the error 'java.lang.IllegalStateException: RecyclerView must not be null'

我有一个 recyclerView,我用我的适配器发送数据但收到错误

RecyclerView must not be null

使用我的适配器代码:

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
    }


}

LinearLayoutManager(this) 的这个错误,说:

`require:Context!
 Founds: InWaitingFragment

您应该将 LinearLayoutManager(this) 更改为 LinearLayoutManager(this.context)

对于您的 LinearLayoutManager,片段不会扩展 Context,因此您不能使用 this 作为参数。相反,使用这个:

waitingRecyclerView.layoutManager = LinearLayoutManager(context!!)

对于运行时错误 "RecyclerView must not be null",这是因为您正在 onCreateView 回调中访问 waitingRecyclerView 的属性。布局尚未初始化。您可以将 waitingRecyclerView 的初始化移动到 'onViewCreated' 回调。

如果您必须在 onCreateView 中初始化 waitingRecyclerView,您可以通过在扩充布局时创建的对象访问 waitingRecyclerView,即 inflate:

inflate.waitingRecyclerView.layoutManager = LinearLayoutManager(context!!)
inflate.waitingRecyclerView.adapter = adapter