Get text from string with kotlin in android studio

4.7k Views Asked by At

I have a kotlin module with code like this.

class AppOpenManager(private val appLanding: AppLanding) : 
    Application.ActivityLifecycleCallbacks, LifecycleObserver{

    //.........OTHER CODE

    companion object {
        private const val TEXT_HEADER = getString(R.string.textheader)
    }

    //.........OTHER CODE
    
}

However I can't get string resource from this code,

private const val TEXT_HEADER = getString(R.string.textheader)

string.xml :

<resources>
    <string name="textheader">Lorem Ipsum</string>
</resources>

Please help so I can fetch string values ​​into kotlin module from resources string.xml Thank you for the help.

2

There are 2 best solutions below

2
Saurabh Dhage On BEST ANSWER

use applications context:

private const val TEXT_HEADER = 
getApplicationContext().getResources().getString(R.string.textheader);
4
Dinkar Kumar On

You cannot use getString like that outside Activity or Application you have to use like below.

context.getString(R.string.textheader)

So you have to have the context to refer to String from string.xml else you won't be able to access it.