How to get a value from resource file in the main Activity class when using fragments?

I’m developing an app with fragments and I want to use a value from “strings.xml” in MainActivity.kt. These are the names of the tabs. But, if I do this:


private var title: String = getText(R.string.title).toString()

I get this error when I run the code:

java.lang.NullPointerException: Attempt to invoke virtual method ‘android.content.res.Resources android.content.Context.getResources()’ on a null object reference

If I do:

private var title = getText(R.string.title)

I also get the error and if I do:

private var title = R.string.title

I get an integer. How can I get the atual text I have in <string name="title">Start</string>?

Hi, this is an Android related question.
Problem is you are calling getText() that needs to have Context which is not available until after the fragment is attached.
So what you can do is call getText() at some other lifecycle time (for example onViewCreated) and the it will work.

Another option is to use. lazy to compute it on first access