如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
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);
当前回答
从意图中获取不同类型的额外信息
要从Intent访问数据,您应该知道两件事。
钥匙数据的DataType。
Intent类中有不同的方法来提取不同类型的数据。看起来像这样
getIntent().XXX(KEY)或intent.XXX(KEY);
因此,如果您知道在otherActivity中设置的变量的数据类型,则可以使用相应的方法。
从Intent检索活动中的字符串的示例
String profileName = getIntent().getStringExtra("SomeKey");
不同数据类型的方法的不同变体列表
您可以在意向正式文档中查看可用方法列表。
其他回答
科特林
第一项活动
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中获取任何类型的额外数据,无论是对象、字符串还是任何类型的数据。
Bundle extra = getIntent().getExtras();
if (extra != null){
String str1 = (String) extra.get("obj"); // get a object
String str2 = extra.getString("string"); //get a string
}
最短的解决方案是:
Boolean isGranted = getIntent().getBooleanExtra("tag", false);
加起来
设置数据
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");
}
在接收活动中
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
不要初始化另一个新的Intent来接收数据,只需执行以下操作:
String id = getIntent().getStringExtra("id");