android.app.NotificationManager: java.lang.NullPointerException

This code:
notificationManager = getSystemService(requireContext(), MyClass::class.java) as NotificationManager

Ends with this error:
java.lang.NullPointerException: null cannot be cast to non-null type android.app.NotificationManager

I searched at the internet hours and hours but without success. What variable/class is null? What i must to do?

Basically, the return value of getSystemService in this case is null. This is because you’re meant to pass in the class of the service that you want, not that MyClass, and so your code should become: getSystemService(requireContext(), NotificationManager::class.java) as NotificationManager

I understand. That makes sense. So what must be return of called class NotificationManager?

There’s getSystemService(Context.NOTIFICATION_SERVICE) at to many example codes on the internet. But Android studio shows error:

Type mismatch.
Required: Context
Found: String

1 Like

Then you need to do getSystemService(requireContext(), Context.NOTIFICATION_SERVICE)

1 Like

Yes! Thank you! I got it! After hours and hours.

val notificationManager = activity?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

notificationManager.notify(NOTIFICATION_ID, builder.build())

It works! :upside_down_face:

1 Like