简体   繁体   中英

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. 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:

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. You should assign a value first and then use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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