Приложение аварийно завершает работу с NullPointerException при удалении отредактированного лекарства с помощью PendingIAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Приложение аварийно завершает работу с NullPointerException при удалении отредактированного лекарства с помощью PendingI

Сообщение Anonymous »

Я работаю над приложением для Android, которое обрабатывает напоминания о лекарствах с помощью уведомлений и сигналов тревоги. Функциональность в основном работает так, как ожидалось:

Код: Выделить всё

I can add a medication.
The notifications are triggered and alarms work fine.
I can delete a medication and the notifications are canceled successfully.
Однако у меня возникла проблема при редактировании лекарства. Вот поведение:

Код: Выделить всё

I add a medication and the notifications and alarms work as expected.
I edit the medication (update its details such as name, quantity, interval, etc.).
After editing, the notifications and alarms still work as they should.
When I attempt to delete the edited medication, the app crashes with a NullPointerException error stating that the PendingIntent is null.
Трассировка стека указывает на следующее:

Код: Выделить всё

java.lang.NullPointerException: cancel() called with a null PendingIntent
at android.app.AlarmManager.cancel(AlarmManager.java:1366)
at com.example.medicamentoreminder.MedicationUtils.cancelAlarm(MedicationUtils.kt:75)
...

Я позаботился о том, чтобы уникальный идентификатор лекарства оставался неизменным в процессе редактирования. Проблема возникает только тогда, когда я удаляю отредактированное лекарство, а не исходное.
Вот основной поток кода:

Код: Выделить всё

Adding a medication:
A PendingIntent is created for scheduling the alarm.
The medication details are saved and alarms are set.

Editing a medication:
The original medication’s data is loaded into the edit fields.
When saving the edited medication, the PendingIntent is updated with the new data and the alarm is re-scheduled.

Deleting a medication:
I attempt to cancel the alarm and notification for the medication being deleted.
The cancelAlarm method is called, but it crashes with a NullPointerException.
Вопрос: Почему PendingIntent имеет значение null при попытке удалить отредактированное лекарство? Что-то мне не хватает при обновлении или отмене PendingIntent после редактирования?
Вот код, относящийся к отмене будильника:

Код: Выделить всё

fun cancelAlarm(context: Context, uniqueID: Int) {

val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context.applicationContext, AlarmReceiver::class.java).apply {
action = "com.example.ALARM_ACTION"  // Custom action to identify the intent
}

val pendingIntent = PendingIntent.getBroadcast(
context.applicationContext,
uniqueID,
intent,
PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE
)

alarmManager.cancel(pendingIntent)
}
А вот код, который назначает сигнал тревоги после редактирования лекарства:

Код: Выделить всё

fun scheduleAlarm(
context: Context,
medication: Medication,
alarmID: Int
) {
// Log para depurar
Log.d("MedicationUtils", "Configurando alarma con alarmID: $alarmID para ${medication.name}")

val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context.applicationContext, AlarmReceiver::class.java).apply {
action = "com.example.ALARM_ACTION"   // Custom action to identify the intent
putExtra("medName", medication.name)
putExtra("quantity", medication.quantity)
}

val pendingIntent = PendingIntent.getBroadcast(
context.applicationContext,
alarmID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

val triggerTime = System.currentTimeMillis() + (medication.intervalInMinutes * 60 * 1000)
val intervalMillis = medication.intervalInMinutes * 60 * 1000L

alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
triggerTime,
intervalMillis,
pendingIntent
)

}
а это для редактирования

Код: Выделить всё

private fun saveUpdatedMedication() {
if (medicationIndex != -1) {
// Primero, obtenemos el medicamento antiguo
val oldMedication = medications[medicationIndex]
MedicationUtils.cancelAlarm(this, oldMedication.uniqueID)
MedicationUtils.cancelNotification(this, oldMedication.uniqueID)
MedicationUtils.deleteMedication(this, medicationIndex, medications)

// Ahora, actualizamos el medicamento con los nuevos valores
val updatedMedication = Medication(
name = nameEditText.text.toString(),
quantity = quantityEditText.text.toString(),
interval = intervalEditText.text.toString(),
intervalInMinutes = MedicationUtils.parseIntervalToMinutes(intervalEditText.text.toString()),
medicationIndex = medicationIndex,
uniqueID = oldMedication.uniqueID
)

// Actualizamos el medicamento en la lista
medications[medicationIndex] = updatedMedication

// Guardamos los cambios en SharedPreferences
MedicationUtils.saveMedications(sharedPreferences, medications)

// Establecemos la nueva alarma para el medicamento editado
MedicationUtils.scheduleAlarm(this, updatedMedication, updatedMedication.uniqueID)

// Devolvemos los datos actualizados a MedicationDetailsActivity
val resultIntent = Intent(applicationContext, AlarmReceiver::class.java).apply {
action = "com.example.ALARM_ACTION"
putExtra("medName", updatedMedication.name)
putExtra("quantity", updatedMedication.quantity)
putExtra("interval", updatedMedication.interval)
putExtra("medicationIndex", medicationIndex)
putExtra("uniqueID", updatedMedication.uniqueID)
}
setResult(RESULT_OK, resultIntent)
finish() // Terminar la actividad después de guardar
}
}
Мы будем очень признательны за любые предложения или идеи о том, почему PendingIntent становится нулевым после редактирования лекарства.

Подробнее здесь: https://stackoverflow.com/questions/791 ... on-with-pe
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»