java Android在两个活动之间传递数据获取NullPointerException
我有3个活动,我们称它们为A、B和C。A和B都有意图将视图发送给C。设计一个C来自不同的事物,在C的活动中发生。我将这样的数据从A传递到C:
Intent intent = new Intent(this, C.class);
intent.putExtra("Action", "A");
startActivity(intent);
在C的onCreate方法中,我有如下内容:
Bundle extras = getIntent().getExtras();
if (extras.getString("Action").equals("A")) {
//DO SOMETHING
}
然后我从B到C我有
Intent intent = new Intent(this, C.class);
startActivity(intent);
然后我得到了NullPointerException,我猜这是因为我从B到C没有指定字符串“Action”
现在,我可以在本例中为B添加一行,但是,如果有更多的活动或大型项目,这将是不好的,因为对于每个活动,我都需要这个
如果不在活动B中添加“Action”sting,我如何才能拥有它,从而不会出现此异常
提前谢谢你的帮助
编辑
如果我从A到C有这个
Intent intent = new Intent(this, C.class);
intent.putExtra("Action", "A");
intent.putExtra("Action2", "A");
startActivity(intent);
这是从B到C
Intent intent = new Intent(this, C.class);
intent.putExtra("Action", "B");
startActivity(intent);
然后在创建C时,从B到C失败:
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.getString("Action").equals("A")) {
//DO SOMETHING
}
else if (extras.getString("Action2").equals("A")) {
//DO Stuuf
}
}
# 1 楼答案
NullPointerException
之所以会发生这种情况,是因为当您从活动A移动到C时,您正在用值传递意图,而在活动C中,您正在使用Bundle获取该值。但当您从活动B移动到C时,您并没有通过intent传递值,而在活动C中您已经编写了这篇文章在这个tme中,额外的值为null,因此您将得到错误
像这样做
编辑 用于从活动传递多个值
在触觉上
# 2 楼答案
试试这个
# 3 楼答案
希望这能解决问题
# 4 楼答案
当您移动到新活动时,总是创建新的意图对象。所以这个问题。尝试以新的意图复制所需的数据并访问它们
# 5 楼答案
像这样更改C类中的代码,以检查bundle是否为null
# 6 楼答案
检查以下代码: