Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

kotlin - How to pass the values from activity to another activity

As I'm learning Kotlin for Android development, I'm now trying the basic programs like hello world and how to navigate from one activity to another activity, there is no issue with this.

When I move from one activity to another, it works fine, but I do not know how to pass the values between the activities.

I tried to set the values in one activity and retrieved them in another activity it does not work.

Please see the code snippet below

This is my main activity where I take the username and password from edit text and setting to the intent:

class MainActivity : AppCompatActivity() {
    val userName = null
    val password = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener {
            val intent = Intent(this@MainActivity,SecondActivity::class.java);
            var userName = username.text?
            var password = password_field.text
            intent.putExtra("Username", userName)
            intent.putExtra("Password", password)
            startActivity(intent);
        }
    }
}

This is my second activity where I have to receive values from the main activity

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        var strUser: String = intent.getStringExtra("Username")
        var strPassword: String = intent.getStringExtra("Password")
        user_name.setText("Seelan")
        passwor_print.setText("Seelan")
    }
}

Please guide me on how to do this, whether I have some other way to do this in Kotlin if not by intent.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Send value from HomeActivity

val intent = Intent(this@HomeActivity,ProfileActivity::class.java)
intent.putExtra("Username","John Doe")
startActivity(intent)

Get values in ProfileActivity

val profileName=intent.getStringExtra("Username")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...