活动onNewIntent空指针异常

时间:2015-09-24 09:11:31

标签: android android-activity nullpointerexception onnewintent

我在我的活动onCreate()中初始化我的列表,如下所示:

private List<MyItem> filtered;
@Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_dashboard);
      filtered = new ArrayList<>();

      // more things
}

当我尝试使用onNewIntent中的过滤项时,有时会得到一个空指针异常。

 @Override
   protected void onNewIntent(Intent intent) {
      super.onNewIntent(intent);
      filtered.clear();
   }

怎么可能?

编辑:我的活动的启动模式是 SingleTask

编辑2:

我无法发送更多有用的日志,因为此崩溃正在生产中。只有我得到一些织物日志。

感谢您的帮助,但我无法粘贴整个代码隐私原因。

我认为我在使用SingleTask-OnCreate-OnNewIntent时遇到问题。我只是试图通过通知打开我的应用程序,并通过参数决定当用户导航到活动时将打开哪个片段。

你有关于这个包含SingleTask-OnCreate-OnNewIntent实现的任何例子吗?

感谢所有人的帮助。

3 个答案:

答案 0 :(得分:2)

Open Whisper Systems的团队遇到了同样的问题:

https://github.com/WhisperSystems/Signal-Android/issues/2971

他们认为,即使您从onNewIntent()内拨打onCreate(),我们也会在finish()后很快就调用onCreate()的Android框架引起这种情况。这最终导致在nullonNewIntent()中使用NullPointerException个对象,因为这些对象尚未在通常onCreate()中设置。这似乎是onCreate()onNewIntent()之间罕见的情况或竞争条件。

他们似乎已通过检查isFinishing()中的onNewIntent()来修复此问题,以阻止onNewIntent()继续:

@Override
protected void onNewIntent(Intent intent) {
    Log.w(TAG, "onNewIntent()");

    if (isFinishing()) {
        Log.w(TAG, "Activity is finishing...");
        return;
    }
    ...
}

来源1:https://github.com/SilenceIM/Silence/commit/c0acae1124c0c066fd961d21d3ec9b989574125d

来源2:https://github.com/SilenceIM/Silence/blob/master/src/org/smssecure/smssecure/ConversationActivity.java#L223

更新: 2017年11月10日:在app / build.gradle中升级构建工具时,这个问题似乎发生得少得多:

buildToolsVersion '25.0.2'

似乎更频繁地使用较旧的构建工具,例如buildToolsVersion '23.0.3',但仍然需要修复,因为它仍然会在极少数情况下发生。

答案 1 :(得分:1)

请记住生命周期,也许您从某些未调用onCreate()的位置返回Activity(例如,如果您在清单中设置了launchMode = singleTask或其他内容)。也许在onResume()中初始化/重新填充你的ArrayList,并检查它是否为null,在返回你的Activity时肯定调用Resume()。

答案 2 :(得分:0)

如果您在NullPointerException方法中获得onNewIntent(),则可能filtered对象为空。

试试这种方式

@Override
protected void onNewIntent(Intent intent) {

   //Check for null value and then proceed. 
   if(filtered != null)
      filtered.clear();
} 
相关问题