Unresolved reference another kotlin class


#1

Hi, I’m learning both kotlin and android with android tutorials on android developer site. (https://developer.android.com/training/basics/firstapp/)
I tried writing ‘build your first app’ in kotlin. but I could not refer main activity’s properties from another activity.
here are my codes.

DisplayMessageActivity.kt

package com.example.my.mynewapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_display_message.textView


class DisplayMessageActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display_message)
        val intent: Intent = getIntent()
        val message: String = intent.getStringExtra(MainActivity.EXTRA_MESSAGE) // this does not work: Unresolved reference
        val message: String = "com.example.mynewapp.MESSAGE" // this works
        textView.text = message
    }
}

MainActivity.kt

package com.example.my.mynewapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.editText

class MainActivity : AppCompatActivity() {
    val EXTRA_MESSAGE: String = "com.example.mynewapp.MESSAGE"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun sendMessage(view: View) {
        val intent = Intent(this@MainActivity, DisplayMessageActivity::class.java)
        val message = editText.text.toString()
        intent.putExtra(EXTRA_MESSAGE, message)
        startActivity(intent)
    }
}

#2

try this
val message: String = intent.getStringExtra(MainActivity().EXTRA_MESSAGE)


#3

Thank you! it works!


#4

You should define EXTRA_MESSAGE as a constant, and certainly not instantiate a new activity for the purpose of getting the value. You want this code:

class MainActivity : AppCompatActivity() {
    companion object {
        const val EXTRA_MESSAGE: String = "com.example.mynewapp.MESSAGE"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun sendMessage(view: View) {
        val intent = Intent(this@MainActivity, DisplayMessageActivity::class.java)
        val message = editText.text.toString()
        intent.putExtra(EXTRA_MESSAGE, message)
        startActivity(intent)
    }
}

#5

Thank you! great!