Ahmed Wagdi
Ahmed Wagdi

Reputation: 4421

How to start an Activity from non Activity view in Android using Kotlin

I need to create new intent and start it from an adapter for a recyclerView kotlin class.

I've tried to addOnClickListener on the item needed. then creating intent and start it.

Here is the code:

        mDressImage1 = itemView.findViewById(R.id.dressImage_1)
        mDressImage1!!.setOnClickListener {
                            val detailsActivity = Intent(context, DressDetailsActivity::class.java)
                        context!!.startActivity(detailsActivity)
                    }

Expected to work normally but return me this error message : Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

and it crashes every time I click the view.

Upvotes: 0

Views: 299

Answers (1)

CodeWithVikas
CodeWithVikas

Reputation: 1443

Main Cause is Your 'context' is null. try using context from 'itemView' like following

mDressImage1 = itemView.findViewById(R.id.dressImage_1)
        mDressImage1!!.setOnClickListener {
                            val detailsActivity = Intent(itemView.getContext(), DressDetailsActivity::class.java)
                        itemView.getContext().startActivity(detailsActivity)
                    }

Vote if it works.

Thanks.

Happy Coding.

Upvotes: 2

Related Questions