如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
当前回答
只是一个建议:
在你的i.putExtra(“id”…..)中不使用“id”或“name”,我建议在有意义的时候,使用当前可以与putExtra一起使用的标准字段,即Intent.EXTRA_shing。
完整的列表可以在Intent(Android开发者)上找到。
其他回答
不要初始化另一个新的Intent来接收数据,只需执行以下操作:
String id = getIntent().getStringExtra("id");
按意图放置数据:
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会给我一个错误。
// 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
在接收活动中
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
在第一项活动中传递带有值的意图:
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”);以获取字符串形式的意向数据,或使用其他可用方法获取其他类型的数据(整型、布尔型等)。关键字可以是任何一个关键字,以标识您共享的价值。希望对你有用。