Android通知空指针
我想创建一个通知,并且我有一段以前可以工作的代码,但现在在最后一行给了我一个空指针。
关于可能导致这种情况的任何想法?
我知道我提供的这段代码可能很难,我只需要提示可能导致此问题的原因。
private void showNotification() {
CharSequence text = getText(R.string.myString);
Notification notification = new Notification(R.drawable.playbackstart, text,
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MyActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.myString),
text, contentIntent);
mNM.notify(R.string.myString, notification);
}
I want to create a notification and I have this bit of code that worked before but now gives me a null pointer at the last line.
Any ideas as to what may cause this?
I know it may be hard with this bit of code that I have provided, I just need a hint as to what could possibly cause this.
private void showNotification() {
CharSequence text = getText(R.string.myString);
Notification notification = new Notification(R.drawable.playbackstart, text,
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MyActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.myString),
text, contentIntent);
mNM.notify(R.string.myString, notification);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我从构造函数中调用
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
时,出现 NullPointerException。我必须将获取
NotificationManager
的调用移至onStart
调用。I was getting a NullPointerException when I called
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
from within the constructor.I had to move the call to get the
NotificationManager
to theonStart
call.mNM 为 null,因为 R.string.myString 必须存在,否则无法编译,并且之前使用了通知,因此不能为 null,否则会提前得到 NPE。因此,检查 mNM。或者发布 mNM 初始化的整个代码。
mNM is null, since R.string.myString must exist otherwise it won't compile, and notification is used before, therefore cannot be null, otherwise would gotten a NPE earlier. Therefore, check mNM. Or post the entire code where mNM is initialized.
而不是使用
您应该在 NOTIFICATION_SERVICE 前面加上 Context,如下所示:
如果你查看Context类的文档,你会发现“static final String NOTIFICATION_SERVICE”的值是“notification”,而不是NOTIFICATION_SERVICE。
因此,仅使用 NOTIFICATION_SERVICE 时出现 NullpointerException 是正常的。
Instead of using
you should prefix the NOTIFICATION_SERVICE with Context, which looks like :
If you look into the documentation of the class Context, you can find that the value of the "static final String NOTIFICATION_SERVICE" is "notification", but not NOTIFICATION_SERVICE.
So it is normal that you get a NullpointerException when only using NOTIFICATION_SERVICE.