I want to start another activity on Android but I get this error:
Please specify constructor invocation; classifier \'Page2\' does not have a companio
Get link to the context of you application
class MY_APPLICATION_NAME: Application() {
companion object {
private lateinit var instance: MY_APPLICATION_NAME
fun getAppContext(): Context = instance.applicationContext
}
override fun onCreate() {
instance = this
super.onCreate()
}
}
object Router {
inline fun <reified T: Activity> start() {
val context = MY_APPLICATION_NAME.getAppContext()
val intent = Intent(context, T::class.java)
context.startActivity(intent)
}
}
// You can start activity from any class: form Application, from any activity, from any fragment and other
Router.start<ANY_ACTIVITY_CLASS>()
Try this
val intent = Intent(this, Page2::class.java)
startActivity(intent)
Remember to add the activity you want to present, to your AndroidManifest.xml too :-) That was the issue for me.
Simply you can start an Activity in KOTLIN by using this simple method,
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", value)
startActivity(intent)
You can generally simplify the specification of the parameter BlahActivity::class.java by defining an inline reified generic function.
inline fun <reified T: Activity> Context.createIntent() =
Intent(this, T::class.java)
Because that lets you do
startActivity(createIntent<Page2>())
Or even simpler
inline fun <reified T: Activity> Activity.startActivity() {
startActivity(createIntent<T>())
}
So it's now
startActivity<Page2>()
To start an Activity in java we wrote Intent(this, Page2.class), basically you have to define Context in first parameter and destination class in second parameter. According to Intent method in source code -
public Intent(Context packageContext, Class<?> cls)
As you can see we have to pass Class<?> type in second parameter.
By writing Intent(this, Page2) we never specify we are going to pass class, we are trying to pass class type which is not acceptable.
Use ::class.java which is alternative of .class in kotlin. Use below code to start your Activity
Intent(this, Page2::class.java)
Example -
val intent = Intent(this, NextActivity::class.java)
// To pass any data to next activity
intent.putExtra("keyIdentifier", value)
// start your next activity
startActivity(intent)