Android Notification NullPointer
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);开发者_StackOverflow社区
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 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 the onStart
call.
@Override
public void onStart(Intent intent, int startId) {
try {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
super.onStart(intent, startId);
}
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.
Instead of using
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
you should prefix the NOTIFICATION_SERVICE with Context, which looks like :
mNM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
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.
精彩评论