Search code examples
androidkotlinandroid-intentandroid-activity

Kotlin Android start new Activity


I want to start another activity on Android but I get this error:

Please specify constructor invocation; classifier 'Page2' does not have a companion object

after instantiating the Intent class. What should I do to correct the error? My code:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun buTestUpdateText2 (view: View) {
        val changePage = Intent(this, Page2) 
        // Error: "Please specify constructor invocation; 
        // classifier 'Page2' does not have a companion object"

        startActivity(changePage)
    }

}

Solution

  • 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 -

    // start your activity by passing the intent
    startActivity(Intent(this, Page2::class.java).apply {
        // you can add values(if any) to pass to the next class or avoid using `.apply`
        putExtra("keyIdentifier", value)
    })