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

我使用此代码发送数据:

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

当前回答

在第一项活动中传递带有值的意图:

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

接收第二项活动的意向-

Intent intent = getIntent();
String user = intent.getStringExtra("uid");
String pass = intent.getStringExtra("pwd");

我们通常使用两种方法来发送值和获取值。对于发送值,我们将使用intent.putExtra(“key”,value);在接收另一个活动的intent期间,我们将使用intent.getStringExtra(“key”);以获取字符串形式的意向数据,或使用其他可用方法获取其他类型的数据(整型、布尔型等)。关键字可以是任何一个关键字,以标识您共享的价值。希望对你有用。

其他回答

不要初始化另一个新的Intent来接收数据,只需执行以下操作:

String id = getIntent().getStringExtra("id");

在接收活动中

Bundle extras = getIntent().getExtras(); 
String userName;

if (extras != null) {
    userName = extras.getString("name");
    // and get whatever type user account id is
}

加起来

设置数据

String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);
startActivity(intent);

获取数据

String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    value = bundle.getString("sample_name");
}

你也可以这样做//将价值放在意图上

    Intent in = new Intent(MainActivity.this, Booked.class);
    in.putExtra("filter", "Booked");
    startActivity(in);

//从意图中获得价值

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String filter = bundle.getString("filter");

首先,使用getIntent()方法获取开始活动的意图:

Intent intent = getIntent();

如果额外的数据表示为字符串,则可以使用intent.getStringExtra(字符串名称)方法。在您的案例中:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");