I want to read strings from an xml file in a source file with no context. Ideally I would like to do something like this: How can I get a resource content from a static context?
However I cannot figure out how to convert that into Kotlin.
I want to read strings from an xml file in a source file with no context. Ideally I would like to do something like this: How can I get a resource content from a static context?
However I cannot figure out how to convert that into Kotlin.
It's basically the same thing. Kotlin isn't too different from Java. In fact, pasting Java code into a Kotlin file in Android Studio will cause a prompt to appear asking if you want to convert that code.
In any case:
The App class:
class App : Application() {
companion object {
var context: Context? = null
}
override fun onCreate() {
super.onCreate()
context = this;
}
}
Then, from any other class:
val context = App.context
val someString = context?.resources.getString(R.string.some_string) //context is nullable so "?" is needed
Remember to add
android:name=".App"
to the application
tag in your AndroidManifest. If App isn't in the root of your package, you'll need to change the value to reflect where it is.
If you need to access it from Java:
App.COMPANION.getContext();
Android Studio may complain about Context leakages. However, that shouldn't be accurate, since the Application Context will be there as long as your app is running, and once your app is killed (or stopped) there's not even a JVM running to have a leak.
You should NEVER make Context static. It's a bad practice and can cause memory leaks and other problems.
By the way in Kotlin static is replaced with "companion object". So your code could look like this. And again - do not store context.
class MyApplication: Application {
override fun onCreate() {
super.onCreate()
sContext = this
}
companion object {
var sContext: Context? = null
}
}
But BETTER way is to store static resources you want, but not context.