我有 3 个 Activity ,我们将其称为 A、B 和 C。A 和 B 都有将 View 发送给 C 的 Intent 。并设计其中一个 C 来自 C 的 Activity 中发生的不同事情。我将这样的数据从 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 添加一行,但是,如果有更多 Activity 或大型项目,这将不好,因为对于每个 Activity ,我都需要它。
如何才能拥有它,以便在不向 Activity B 添加“操作”字符串的情况下不会出现此异常?
感谢您提前提供的帮助。
编辑
如果我从 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 的 onCreate 中从 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
}
}
最佳答案
像这样更改 C 类中的代码以检查包是否为空。
Bundle extras = getIntent().getExtras();
if(extras != null){
if(extras.getString("Action") != null)
if (extras.getString("Action").equals("A")) {
//DO SOMETHING
}
}
if(extras.getString("Action2") != null)
if (extras.getString("Action2").equals("A2")) {
//DO SOMETHING
}
}
}
关于java - Android - 在两个 Activity 之间传递数据得到 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27286937/