如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
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);
当前回答
如果您试图获取碎片中的额外数据,则可以尝试使用:
放置数据时使用:
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
使用以下方法获取数据:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}
其他回答
在接收活动中
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”);以获取字符串形式的意向数据,或使用其他可用方法获取其他类型的数据(整型、布尔型等)。关键字可以是任何一个关键字,以标识您共享的价值。希望对你有用。
从意图中获取不同类型的额外信息
要从Intent访问数据,您应该知道两件事。
钥匙数据的DataType。
Intent类中有不同的方法来提取不同类型的数据。看起来像这样
getIntent().XXX(KEY)或intent.XXX(KEY);
因此,如果您知道在otherActivity中设置的变量的数据类型,则可以使用相应的方法。
从Intent检索活动中的字符串的示例
String profileName = getIntent().getStringExtra("SomeKey");
不同数据类型的方法的不同变体列表
您可以在意向正式文档中查看可用方法列表。
加起来
设置数据
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 args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
使用以下方法获取数据:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}