【问题标题】:IntentService - NullPointerExecption on startService [duplicate]IntentService - startService 上的 NullPointerExecption [重复]
【发布时间】:2016-09-14 06:18:20
【问题描述】:

我正在尝试使用 Android 提供的IntentService 功能尝试在后台运行一些计算

我从昨天开始一直在研究这个问题,但我似乎找不到任何有效的解决方案。
我已经查看了很多关于 IntentService 的 SO 问题,并尝试应用建议的修复程序,但我的似乎无法正常工作。

我尝试从调用函数的 Activity 中传入各种不同的 context / Activies / getApplicationContext() / this / getBaseContext(),但我仍然得到一个 null 对象引用错误

"尝试调用虚拟方法'android.content.ComponentName android.content.Context.startService(android.content.Intent)' 在一个 空对象引用”

应用程序在调用 startService() 的函数的第 3 行崩溃(请参阅下面的代码)

//This function is from MyCurrentClass.class - it is a Singleton and its being called from another activity where it passes in its context
public void notify (Context context, JSONObject responseFromDb){

    Intent inputIntent = new Intent(context, MyCurrentClass.class);
    inputIntent.putExtra("responseFromDB", responseFromDb.toString());
    this.startService(inputIntent); //crashes here!
}

P.S.:我看过的大多数解决方案似乎只有 1 个 Activity,但我的应用正在不同的 Activity 之间切换。 (不确定这是否重要)但最重要的是我正在处理的类是一个扩展 IntentService 的普通 Java 类,它不是一个 Activity 类

我还在我的 Android 清单中声明了该服务以链接到 MyCurrentClass,并从 Activity 中尝试了bindService():它被调用了,但它也不起作用。

以下是我查看并尝试但失败的一些问题/解决方案:

其实我看过很多其他的帖子,但是太多了。

希望我提供的信息已经足够。如果不是,请让我知道可能缺少什么,我将使用所需信息更新问题。

【问题讨论】:

  • 请显示minimal reproducible examplethis 是什么?同时显示清单
  • 在您传递给方法的Context 上调用startService()。此外,如果您将Context 传递给MyCurrentClass,则可能不应该是Context 本身,而您的方法可能是static
  • @MikeM。问题...为什么this.startService 会为Context.startService 抛出NPE?那不是说this 为空,这真的不可能吗?
  • @cricket_007 无论MyCurrentClass 是什么类型,我都假设它最终是一个ContextWrapper,它保留了一个Context 字段,实际上调用了startService()startActivity() 之类的方法。当系统没有正确实例化这样的类时,该字段为空,因此为 NPE。
  • @PavneetSingh yupp :) 我也从他/她的 POV 中理解,但这实际上是因为我在 24 小时内一直在寻找问题本身并且一直无法解决它,这就是我决定来这里寻求帮助>

标签: java android android-intent nullpointerexception android-intentservice


【解决方案1】:

使用context 您在从活动中收到的 cmets 中提到的类似内容,因为在这种情况下,您当前的课程没有上下文。read for further details

context.startService(inputIntent); 

而不是

this.startService(inputIntent); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多