You need to be careful assigning top-level variables in things like Activities
and Fragments
with expressions that require a Context
. They don't have one at construction time, the system provides that later - that's how you end up seeing this kind of error (in your case, it's trying to call getResources()
on something that should be a Context
, but it's actually null).
A fragment's Context
has been attached by the time it enters the CREATED state, so it's safe to access it in onCreate
or later. So you can make your top-level variable lateinit
(deferring assignment) and set the value on it later:
// define the variable without a value - you need to set a value before this is read!
private lateinit var title: String
override fun onCreate(savedInstanceState: Bundle?) {
...
// assign the value when you can
title = getText(R.string.title).toString()
}
Or you could use a lazy
delegate, which will set the value the first time the variable is accessed, by running a setter function:
private val title: String by lazy {
getText(R.string.title).toString()
}
This will fail if the function is called before the Context
is available too, so in both situations you have to be able to guarantee nothing will try to read from it too early. The lazy
is arguably neater (no separate assignment) but it does make the value read-only, instead of a var
- that's probably fine in this situation!
Also if you specifically want a String
instead of a CharSequence
, just call getString
instead of getText