【发布时间】:2016-12-24 14:43:06
【问题描述】:
我一直在尝试使用 Intent 在两个活动之间传递多个值(不同类型的)。到目前为止,我已经尝试了这两种方法:
Intent intent = new Intent(context, Receiver.class);
Bundle bundle = new Bundle();
bundle.putInt("key1", v1);
bundle.putString("key2", v2);
bundle.putString("key3", v3);
bundle.putInt("key4", v4);
intent.putExtras(bundle);
和:
Intent intent = new Intent(context, Receiver.class);
intent.putInt("key1", v1);
intent.putString("key2", v2);
intent.putString("key3", v3);
intent.putInt("key4", v4);
但是,似乎在这两种情况下都只保留了 key1 的值(使用 Bundle 时,它显然只包含 1 个键)。我错过了什么?
编辑:这就是我在Receiver中检索值的方式:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
v1 = bundle.getInt("key1", DEFAULT1);
v2 = bundle.getString("key2", "DEFAULT2");
v3 = bundle.getString("key3", "DEFAULT3");
v4 = bundle.getInt("key4", DEFAULT4);
// ...
}
或者:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Intent intent = getIntent();
v1 = intent.getIntExtra("key1", DEFAULT1);
v2 = intent.getStringExtra("key2");
v3 = intent.getStringExtra("key3");
v4 = intent.getIntExtra("key4", DEFAULT2);
// ...
}
当我打印出v1、v2、v3 和v4 的值时,v1 是唯一一个具有非空/非默认值的值(我最初输入的值)在key1 - 实际上,我最初放入 Intent 的所有值都是非默认值。
编辑 2:
我尝试像这样使用getBundleExtra():
intent.putExtra("bundle", bundle);
然后在Receiver:
Bundle bundle = intent.getBundleExtra("bundle");
但是,bundle 为空。
编辑 3:
更改从 Intent 中放入/检索值的顺序似乎不会影响任何事情。也没有指定 Bundle 的容量。如果有帮助,此 Intent 将用于 PendingIntent。
【问题讨论】:
-
“但是,似乎只有 key1 的值在这两种情况下都被保留了”——您如何确定这一点?
-
你如何检索值?
-
用代码编辑了我的问题 - 我只是使用
getExtras()作为捆绑包,如果没有捆绑包则使用getExtra。此外,我打印出所有检索到的值,并将它们与默认值进行比较。 -
这不太可能。我定期这样做,没有任何问题。问题可能出在其他地方。发布这两项活动的完整代码。
标签: android android-intent bundle