0

I am trying to set the Snacksbar message and action texts with values from strings.xml. If I call .toString() on the values it will obviously be set to some random numbers, as expected. I can't get a reference to context, because it isn't a composable function, so I can't use LocalContext.current meaning I cannot access .getString(). How do I set the value of the message and action properly?

fun onEvent(event: TaskListEvent) {
        when (event) {
            is TaskListEvent.OnDeleteTask -> {
            viewModelScope.launch(Dispatchers.IO) {
                deletedTask = event.task
                repository.deleteTask(event.task)
                sendUiEvent(
                    UiEvent.ShowSnackbar(
                        message = "Task successfully deleted!", action = "Undo"
                    )
                )
        }

}
Juncu
  • 3,704
  • 4
  • 7
  • 27

1 Answers1

0

It looks like you need an Application class so you can get context when you need it. You have to set the android:name in the application tag in the manifest to the Application class that you use

Something like,

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    val context: Context
        get() = this

   companion object {
        var instance: MyApplication? = null
            private set
   }
}

the Usage for this class is

MyApplication.instance
MyApplication.instance?.context
CCT
  • 70
  • 1
  • 6
  • Mind you the use for this will be `MyApplication.instance?.context` because it is nullable. Except for this everything is correct! – Juncu Feb 08 '23 at 16:00