Pablo
06/25/2024, 7:14 PMapplicationContext
return null? I'm getting null when calling it. This is my Application class:
class MyApplication: Application() {
lateinit var container: AppContainer
override fun onCreate() {
super.onCreate()
container = AppContainer()
}
}
//Extension function that returns an instance of Application
fun CreationExtras.MyApplication(): MyApplication =
(this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as MyApplication)
And this is how I get it:
MyApplication().applicationContext
Meet
06/26/2024, 4:54 AMapplicationContext
directly from any Context
(like an Activity
or Service
):
val appContext = context.applicationContext as MyApplication
Pablo
06/26/2024, 6:29 AMPablo
06/26/2024, 6:29 AMPablo
06/26/2024, 6:29 AMswanti
06/26/2024, 10:27 AMMyApplication
is the app's Application in the AndroidManifest? Something like:
<application
android:name=".MyApplication"
The .
is because the class is in the project root, if it's in a different package you will have to do something like .mypackage.MyApplication
Pablo
06/26/2024, 11:08 AMswanti
06/26/2024, 11:49 AMapplicationContext
in a Service
? If not, the only thing I can suggest is that you implement the suggestion in https://stackoverflow.com/questions/21994612/get-application-context-returns-null which is your exact questionPablo
06/26/2024, 4:26 PMswanti
06/26/2024, 4:28 PMapplicationContext
before the App has been created. When are you trying to access the context?Pablo
06/26/2024, 4:28 PMswanti
06/26/2024, 4:33 PMPablo
06/26/2024, 4:35 PM@Composable
fun LoadingScreen(
viewModel: LoadingScreenViewModel = viewModel(factory = LoadingScreenViewModel.factory(LocalContext.current)),
modifier: Modifier = Modifier
)
in the constructor of the first Composable I'm getting it.swanti
06/26/2024, 4:38 PMswanti
06/26/2024, 4:39 PMPablo
06/26/2024, 4:40 PMPablo
06/26/2024, 4:40 PMPablo
06/26/2024, 4:41 PMval uiState = viewModel.uiState
Pablo
06/26/2024, 4:42 PMPablo
06/26/2024, 4:42 PMPablo
06/26/2024, 4:44 PMswanti
06/26/2024, 4:44 PM