如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
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);
当前回答
加起来
设置数据
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");
}
其他回答
首先,使用getIntent()方法获取开始活动的意图:
Intent intent = getIntent();
如果额外的数据表示为字符串,则可以使用intent.getStringExtra(字符串名称)方法。在您的案例中:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("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");
科特林
第一项活动
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"
}
加起来
设置数据
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");
}
// 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