简体   繁体   English

lateinit 属性 ABC 尚未初始化

[英]lateinit property ABC has not been initialized

After clicking button I've implemented in recyclerView belongs to activity_main.xml (MainActivity class), which work is to switch activities (MainActivity -> EmployeeActivity), it shows a problem below.我在recyclerView中实现的按钮点击后属于activity_main.xml(MainActivity类),它的工作是切换活动(MainActivity -> EmployeeActivity),下面显示了一个问题。 I would be grateful for every tips.我将不胜感激每一个提示。

Error:错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ing, PID: 31027
    kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
        at com.example.ing.adapter.MyAdapter.getContext(MyAdapter.kt:20)
        at com.example.ing.adapter.MyAdapter$onBindViewHolder$1.onClick(MyAdapter.kt:37)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

MyAdapter class: MyAdapter 类:

class MyAdapter :RecyclerView.Adapter<MyAdapter.MyViewHolder>(){

    lateinit var context:Context

    private var myList = emptyList<Data>()
    inner class MyViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.layout_employee_item, parent, false))
    }

    override fun getItemCount(): Int {
        return myList.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.itemView.tvEmployeeName.text = myList[position].employeeName
        holder.itemView.showButton.setOnClickListener{
            val intent = Intent(context.applicationContext,EmployeeActivity::class.java)
            intent.putExtra("id", position)
            context.startActivity(intent)

        }
    }

    fun setData(newList:List<Data>){
        myList = newList
        notifyDataSetChanged()
    }
}

You declared lateinit var context:Context variable, but you have not assigned any context value to it.您声明了lateinit var context:Context变量,但尚未为其分配任何上下文值。 You should assign a value first and then use it.您应该先分配一个值,然后再使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM