1

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.

M.Fahri
  • 345
  • 3
  • 11

2 Answers2

2

use applications context:

private const val TEXT_HEADER = 
getApplicationContext().getResources().getString(R.string.textheader);
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31
0

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.

Dinkar Kumar
  • 2,175
  • 2
  • 12
  • 22
  • I have error: Unresolved reference: getString – M.Fahri Jun 10 '21 at 19:08
  • You used the `context.getString(R.string.textheader)` by having access to context where ever you were extracting the value? – Dinkar Kumar Jun 10 '21 at 20:39
  • Sorry, but I really don't understand how. I can extract the value from string.xml on "Main Activity.kt". Then I created a new kotlin module, but it can't do the same to extract the string.xml value in this module. – M.Fahri Jun 11 '21 at 00:22
  • As i said you cannot use getString as it is outside of Activity or Application classes, you have to use `context.getString` – Dinkar Kumar Jun 11 '21 at 03:00