java - Android - 在两个 Activity 之间传递数据得到 NullPointerException

标签 java android android-intent android-activity nullpointerexception

我有 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/

相关文章:

java - iTextPDF:动态更改表格对齐方式

android - event.getAction() 从不使用 MotionEvent.ACTION_UP

android - 在我的应用程序中处理下载 Intent

android - 我想分享带有单个字幕的多张图片

java - 如何以非递归方式重写 Ackermann 函数?

java - 打开主页应用程序打不开

java - 如何将JButton移动到特定位置

android - 在 android 中使用 Smack 的 ejabberd 连接给出连接超时错误

android - 为 Android 发送带附件的 HTML 电子邮件

android - Intent extra 即使在更新后也保持不变