call getString(R.strings....) from class? call getString(R.strings....) from class? android android

call getString(R.strings....) from class?


getString() is a method of the Context class¹. If you need it inside a seperate class (that does not extend Context), it's usually best to provide it as a seperate argument to the method that needs it.

Example:

public void logString(Context c, int stringId) {    Log.d("TAG", c.getString(stringId));}

One thing is important: Never store the context inside the separate class.
Provide an argument. Otherwise you will leak memory and disrupt the whole android lifecycle if the object that stores the context lives longer than the object where the context originally belongs to (e.g. an activity).

¹ getString() can also be used from the Resources class - which you can get via Context.getResources()


the solution here is to make sure your object has a reference to the application context

Class Swag{    private Context ctx;    public Swag(Context ctx){       this.ctx = ctx;    }    public void doSomething(){        String something = ctx.getResources().getString(R.string.somestring);        ...    }    // or like this    public void makeUpperCase(Context appContext){        appContext.getResources().getString(R.string.super_string_swag_yolo);    }}

obviously you'd have to supply the context when creating an object or when caling the method


resouce file: values/strings.xml

<resources>   <string name="app_name">App name</string><resources>

java

import android.content.res.Resources;Resources.getSystem().getString(R.string.app_name);//result : App name