错误:尝试调用虚拟方法';java.lang.Object android.content.Context.getSystemService(java.lang.String)和#x27;关于空对象引用

错误:尝试调用虚拟方法';java.lang.Object android.content.Context.getSystemService(java.lang.String)和#x27;关于空对象引用,java,android,Java,Android,也有类似的问题,但在撞了我的头之后,我无法解决这个问题。我得到以下错误!是碎片造成的吗 public class AlarmTask implements Runnable{ // The date selected for the alarm private final Calendar date; // The android system alarm manager private final AlarmManager am; // Your context to retrieve the

也有类似的问题,但在撞了我的头之后,我无法解决这个问题。我得到以下错误!是碎片造成的吗

public class AlarmTask implements Runnable{
// The date selected for the alarm
private final Calendar date;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;

public AlarmTask(Context context, Calendar date) {

    this.context = context;
    this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); //error for this line
    this.date = date;
}
这就是我调用setAlarm函数的地方

 public void setAlarm(Calendar c) {
    // This starts a new thread to set the alarm
    // You want to push off your tasks onto a new thread to free up the UI to carry on responding
    new AlarmTask(this, c).run();
}

您可以使用
getActivity()
,它返回与片段关联的活动。 因此,您的代码将成为:

  public void setAlarmForNotification(Calendar c){
    ScheduleService mBoundService = new ScheduleService();
    mBoundService.setAlarm(c);
         }
在代码中

public AlarmTask(Calendar date) {
this.am = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE); //error for this line
this.date = date;
}
上下文
null

检查堆栈跟踪您正在初始化中的
AlarmTask

this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

onActivityCreated
方法中移动此调用。

如果您在不同片段中返回到片段,并且在返回到片段时执行导致错误的方法

at lol.com.epl.FixFragment.onCreateView(FixFragment.java:88)
将该方法包装在

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

问题将得到解决。

您的上下文为空。张贴你是如何调用这个类的,你可以在哪里用这个代码有一个NPE。这取决于调用getActivity()的时间。您可以在尚未定义活动时调用它。getActivity()返回null的情况是什么?在这篇文章中帮助我的是明确观察到context==null为true。我在if语句中检查了上下文对象是否为null,并解决了问题。谢谢
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
if (getActivity() != null) {
// Code goes here.
}