0

Im trying to proceed on the next activty from Kotlin to Java it gives me a red line in ".java" in

 val intent = Intent(this, MainActivity::class.java)
 startActivity(intent)

This is my whole code:

package com.heyletscode.artutorial


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button

class Garlic : AppCompatActivity() {
lateinit var button : Button


 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_garlic)
    button = findViewById(R.id.Button)
    button.setOnClickListener(listener)
 }
 val listener= View.OnClickListener { view ->
    when (view.getId()) {
        R.id.Button -> {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
    }
 }


 }

Ive tried different methods to proceed to next activty but give me red line in .java

2 Answers 2

1

I'd suggest moving your listener set-up to your onCreate like this

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_garlic)
        button = findViewById(R.id.Button)
        button.setOnClickListener {  ->
            val intent = Intent(this@Garlic, MainActivity::class.java)
            startActivity(intent)
        }
    }

and the this is referencing to your onClickListener, append it with @ followed by your activity name

val intent = Intent(this@Garlic, MainActivity::class.java)
Sign up to request clarification or add additional context in comments.

Comments

0

may be you provide wrong context to Intent try below code

package com.heyletscode.artutorial


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button

class Garlic : AppCompatActivity() {
lateinit var button : Button
 private lateinit var context: Context //create object of context


 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_garlic)
    context= this@MainActivity   //  init context here
    button = findViewById(R.id.Button)
    button.setOnClickListener(listener)
 }
 val listener= View.OnClickListener { view ->
    when (view.getId()) {
        R.id.Button -> {
            val intent = Intent(context, MainActivity::class.java) //replace this with context
            startActivity(intent)
        }
    }
 }


 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.