PendingIntent null当试图从类中调用它
问题描述:
Im bulding一个闹钟,我得到一个pendingIntent,应该使闹钟暂停。当它在活动中时,相同的代码工作得很好。我改变了一些东西,现在改成了另外一类。我得到一个nullpointerExecption。 (承包商获得从活动上下文PendingIntent null当试图从类中调用它
暂停功能:
public void settingNewIntentForSnooze() {
PendingIntent alarmPendingIntent=null;
Calendar calendar = Calendar.getInstance();
// new alarm after the snooze.
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + snoozeTime);
Intent snoozeIntent = new Intent(context, Alarm_Reciver.class);
snoozeIntent.putExtra("click_status", true);
//add that to try to solve the problem...
snoozeIntent.setAction("Snooze");
alarmPendingIntent = PendingIntent.getBroadcast(context, 0, snoozeIntent, alarmPendingIntent.FLAG_ONE_SHOT);
//tells to phone to set the alarm
alarm_manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmPendingIntent);
}
AlarmPage活性(即外币的变量的代码):
snooze= new Snooze(this,alarm_manager);
AlarmReciver:
public void onReceive(Context context, Intent intent) {
Log.e("in alarm reciver","in alarm reciver");
Intent service_intent= new Intent(context, RingtonePlayingService.class);//intent for the service ringtone playing
boolean button_status = intent.getExtras().getBoolean("click_status");
service_intent.putExtra("click_status", button_status);//passing button status
context.startService(service_intent);//start the ringtone service
}
错误:
09-17 18:25:25.564 1563-1563/com.example.itay.newfrindlyalarm E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.itay.newfrindlyalarm, PID: 1563
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.AlarmManager.set(int, long, android.app.PendingIntent)' on a null object reference
at com.example.itay.newfrindlyalarm.Snooze.settingNewIntentForSnooze(Snooze.java:60)
at com.example.itay.newfrindlyalarm.Snooze.operate(Snooze.java:44)
at com.example.itay.newfrindlyalarm.AlarmPage.operateSnooze(AlarmPage.java:88)
at com.example.itay.newfrindlyalarm.AlarmPage$3.onClick(AlarmPage.java:68)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
enter code here
答
根据错误信息判断,有没有可能alarm_manager
是null
?如果您正确初始化AlarmManager
,错误会消失吗?
+0
是的,我刚刚创建了一个贪睡对象,然后才初始化我输入到他的构造函数中的AlarmManager ..我花了两个小时处理这个错误,现在我看到了它的简单性。非常感谢! –
为什么你要在第一行定义'alarmPendingInten = null',但是当你可以'getBroadcast'后再覆盖它呢?这是不好的风格:) –
'settingNewIntentForSnooze'方法中'context'的值是什么?它有很好的价值吗? –
请添加您的错误信息。这是很难调试代码没有看到错误:) –