Cathie B
Cathie B

Reputation: 3

New to coding; Can't get button to link to new activity in Kotlin

It opens the first activity on the emulator, but fails on button click. I created the second activity (AddProductActivity), so maybe I did something wrong there. I've tried all the variables I could find online to change how the button operates.

class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.content_main)
       val button = findViewById<Button>(R.id.goToAddProduct)
       button.setOnClickListener {
       val intent = Intent(this, AddProductActivity::class.java)
           startActivity(intent)
       }
   }
}

class AddProductActivity: AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.add_product)
   }
}

on content_main.xml:

    <Button
        android:id="@+id/goToAddProduct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add_to_inventory"/>

Upvotes: 0

Views: 593

Answers (1)

saiful103a
saiful103a

Reputation: 1129

Make sure you have registered your new activity in the manifest. This is a common mistake by newcomers.

android manifest xml

If that is not the case before you click on the button open your logcat view in android studio. Once you click on the button please investigate the crash issue from here.

logcat view on android studio

Upvotes: 1

Related Questions