如何将数据从一个活动(意图)发送到另一个活动?

我使用此代码发送数据:

Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);

当前回答

科特林

第一项活动

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

第二项活动

val value = getIntent().getStringExtra("key")

建议

始终将密钥放在常量文件中,以便于管理。

companion object {
    val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}

其他回答

从意图中获取不同类型的额外信息

要从Intent访问数据,您应该知道两件事。

钥匙数据的DataType。

Intent类中有不同的方法来提取不同类型的数据。看起来像这样

getIntent().XXX(KEY)或intent.XXX(KEY);

因此,如果您知道在otherActivity中设置的变量的数据类型,则可以使用相应的方法。

从Intent检索活动中的字符串的示例

String profileName = getIntent().getStringExtra("SomeKey");

不同数据类型的方法的不同变体列表

您可以在意向正式文档中查看可用方法列表。

只是一个建议:

在你的i.putExtra(“id”…..)中不使用“id”或“name”,我建议在有意义的时候,使用当前可以与putExtra一起使用的标准字段,即Intent.EXTRA_shing。

完整的列表可以在Intent(Android开发者)上找到。

按意图放置数据:

Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);

按意图获取数据:

String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);

如果我们对意图使用整数值,则必须在getIntent().getIntExtra(“instituteId”,0)中将第二个参数设置为0。否则,我们不使用0,Android会给我一个错误。

我们可以通过简单的方法做到这一点:

在FirstActivity中:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

在SecondActivity中:

    try {
        Intent intent = getIntent();

        String uid = intent.getStringExtra("uid");
        String pwd = intent.getStringExtra("pwd");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("getStringExtra_EX", e + "");
    }
//  How to send value using intent from one class to another class
//  class A(which will send data)
    Intent theIntent = new Intent(this, B.class);
    theIntent.putExtra("name", john);
    startActivity(theIntent);
//  How to get these values in another class
//  Class B
    Intent i= getIntent();
    i.getStringExtra("name");
//  if you log here i than you will get the value of i i.e. john