'NullPointerException when i call SmsManager.sendTextMessage() method

When this line is executed:

val smsManager = context.getSystemService(SmsManager::class.java)

I am getting this exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.telephony.SmsManager.sendTextMessage(java.lang.String, java.lang.String, java.lang.String, android.app.PendingIntent, android.app.PendingIntent)' on a null object reference

However when I call this other line which is the decreped version it works fine

val smsManager= SmsManager.getDefault()

I suspect it must be something to do with the context or the way I'm injecting it.

This is the complete class:

class PhoneStateListenerClass @Inject constructor(
@ApplicationContext private val context: Context,): PhoneStateListener() {

override fun onCallStateChanged(state: Int, incomingNumber: String) {
    if(state==TelephonyManager.CALL_STATE_RINGING){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val smsManager = context.getSystemService(SmsManager::class.java)
                smsManager.sendTextMessage(incomingNumber,null,phone.message,null,null)
            }
            else{
                val smsManager= SmsManager.getDefault()
                smsManager.sendTextMessage(incomingNumber,null,phone.message,null,null)
            }
}
}
}
}

UPDATE

Even if i execute these lines:

 val smsManager = context.getSystemService(SmsManager::class.java)
                smsManager.sendTextMessage(incomingNumber,null,phone.message,null,null)

I have the same error...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source