如何解决错误“ java.lang.IllegalStateException:RecyclerView不能为空”

时间:2019-05-15 14:59:43

标签: kotlin android-recyclerview linearlayoutmanager

我有一个recyclerView,我在其中使用适配器发送数据,但收到错误

  

RecyclerView must not be null

使用我的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
    }


}

LinearLayoutManager(this)上遇到了错误,说:

`require:Context!
 Founds: InWaitingFragment

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

waitingRecyclerView.layoutManager = LinearLayoutManager(context!!)

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

如果必须在waitingRecyclerView内初始化onCreateView,则可以通过在扩展版面时创建的对象访问waitingRecyclerView,即inflate

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