如何将值从活动传递到另一个活动

如何将值从活动传递到另一个活动

问题描述:

因为我正在学习用于 Android 开发的 Kotlin,我现在正在尝试基本程序,如 hello world 以及如何从一个活动导航到另一个活动,这没有问题.

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.

请看下面的代码片段

这是我的主要活动,我从编辑文本和设置中获取用户名和密码到意图:

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

请指导我如何做到这一点,如果不是故意的,我是否有其他方法可以在 Kotlin 中做到这一点.

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

从 HomeActivity 发送值

Send value from HomeActivity

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

在 ProfileActivity 中获取值

Get values in ProfileActivity

val profileName=intent.getStringExtra("Username")