3

I have the following inside a @composable function. I am getting an error with the previews. I am not sure this works on a device either.

val context = LocalContext.current
val noteTrainerViewModel = NoteTrainerViewModel(context.applicationContext as Application)

And here is the error:

java.lang.ClassCastException: class com.android.layoutlib.bridge.android.BridgeContext cannot be cast to class android.app.Application
james
  • 2,595
  • 9
  • 43
  • 70

1 Answers1

3

This happens because in preview there's no Application running. You cannot use methods that depend on Application during preview

On a real run this code will work fine

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • what is the workaround for this, since I am not able to see the preview of my composable and I can't work on UI – Notron May 09 '23 at 11:58
  • @Notron check out [this answer](https://stackoverflow.com/a/70163730/3585796) on how to check if composable is run from preview – Phil Dukhov May 09 '23 at 12:34