M.Fahri
M.Fahri

Reputation: 375

Get text from string with kotlin in android studio

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.

Upvotes: 1

Views: 5262

Answers (2)

Saurabh Dhage
Saurabh Dhage

Reputation: 1711

use applications context:

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

Upvotes: 3

Dinkar Kumar
Dinkar Kumar

Reputation: 2250

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.

Upvotes: 1

Related Questions