2

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...

devblock
  • 113
  • 7
  • Is your smsManager null after calling `context.getSystemService(SmsManager::class.java)` ? – Ionut Jul 07 '22 at 15:20
  • 3
    Your version check should be for `Build.VERSION_CODES.S`, not `M`; i.e., `if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {`. The `getDefault()` method wasn't deprecated until API level 31: https://developer.android.com/reference/android/telephony/SmsManager#getDefault(). – Mike M. Jul 09 '22 at 21:01

1 Answers1

-1

Either of the Argument is having null value

incomingNumber

or

phone.message

is having null value.

Yahya M
  • 392
  • 3
  • 13