private fun getSmsManagerForSubscriptionId(context: Context, subsId: Int): SmsManager {
val smsManager = if (Build.VERSION.SDK_INT >= M) {
context.getSystemService(SmsManager::class.java) as SmsManager
} else {
TODO("VERSION.SDK_INT < M")
}
val smsManagerInstanceForSubsId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
smsManager.createForSubscriptionId(subsId)
} else {
TODO("VERSION.SDK_INT < S")
}
return smsManagerInstanceForSubsId
}
I am using above code to create an smsManager Instance but the code is showing error at
context.getSystemService(SmsManager::class.java) as SmsManager
below is the error it is showing
Cannot cast null object to non-null object.
2
Answers
I didn’t get any null exceptions when I ran it
The error you’re encountering suggests that the
getSystemService
method is returning a null object, and you’re trying to cast it to a non-nullSmsManager
object. This can happen if the system service forSmsManager
is not available or accessible in the givenContext
.To handle this situation, you can modify your code as follows:
Instead of using
SmsManager::class.java
, you can directly useContext.SMS_SERVICE
as the argument togetSystemService()
. This ensures that the system service for SMS is retrieved correctly, regardless of the Kotlin version you’re using.Make sure that you have the necessary permissions declared in your AndroidManifest.xml file to access the SMS functionality, such as
<uses-permission android:name="android.permission.SEND_SMS" />
.