Home > OS >  Android toast displaying incorrect String value
Android toast displaying incorrect String value

Time:07-05

When setting a switch as off the user should receive a toast saying "alarm set for 00.40" for example, but for some reason the "alarm set for" has been swapped out for a string of numbers as below.

enter image description here

The code:

            override fun setSwitchOn(alarm: Alarm) {
            val toastTime = formatTime(alarm)
            val alarmManager = AlarmManager(
                alarm.id,
                alarm.hour,
                alarm.minute,
                true,
                alarm.repeat,
            )
            alarmManager.cancel(requireContext())
            Toast.makeText(
                context,
                "${R.string.toast_alarm_set} $toastTime",
                Toast.LENGTH_SHORT
            ).show()
        }

        override fun setSwitchOff(alarm: Alarm) {
            val alarmManager = AlarmManager(
                alarm.id,
                alarm.hour,
                alarm.minute,
                true,
                alarm.repeat,
            )
            alarmManager.cancel(requireContext())
            Toast.makeText(context, R.string.toast_alarm_cancelled, Toast.LENGTH_SHORT).show()
        }
    })

and the string resources:

<resources>
    <string name="app_name">App</string>

    // home screen

    <string name="next_alarm">Next Alarm</string>
    <string name="daily_alarm">Daily</string>
    <string name="once_alarm">Once</string>
    <string name="title_delete">Delete Alarm?</string>
    <string name="delete_builder_delete">Delete</string>
    <string name="delete_builder_alarm_deleted">Alarm Deleted</string>
    <!--    this line below -->
    <string name="toast_alarm_set">Alarm set for</string>

all others work perfectly, and changing the content of the string here does nothing.

CodePudding user response:

You cannot use string resources inside a string literal like

val mystr = "${R.string.somestring} days"

you have to actually call getString there to get the string (R.string.somestring is just an integer resource ID). It should look like this

val mystr = "${context.getString(R.string.somestring)} days"

or in your case

"${context.getString(R.string.toast_alarm_set)} $toastTime"

If you pass an integer string resource ID to a toast directly (like you do with the alarm cancelled case) it automatically calls getString internally, but if you pass in a string it does not do any transformations, so you have to do that yourself.

CodePudding user response:

Toast.makeText(context, "alarm set for" R.string.toast_alarm_cancelled, Toast.LENGTH_SHORT).show();

//i think may be its work //may i can help if you provide toast_alarm_cancelled

  • Related