Home > OS >  Intent from kotlin to java Error in class.java
Intent from kotlin to java Error in class.java

Time:11-05

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

CodePudding user response:

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)

CodePudding user response:

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)
        }
    }
 }


 }
  • Related