36

In my Java class I want to use a string resource from strings.xml.

For that I want to use something like this:

getString(R.string.address)

If my class is an activity then it's working.
But how can I use it if my class is a simple Java class?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Narendra
  • 1,868
  • 6
  • 25
  • 39

4 Answers4

52

A class does not have a context and to use a string resource a context is needed. So just call the class from an activity and give a parameter context and within your class constructor just use that context to get the string resource.

In your custom class you need to import the R namespace for the project to get the resource Id.

import com.myrandomapp.R;

Then to get the actual string

context.getString(R.string.COOL_STRING)
hanut
  • 505
  • 4
  • 24
Jyosna
  • 4,436
  • 13
  • 60
  • 93
  • 17
    This answer is incomplete - To complete for those who still have questions, you need to import the R namespace for the project to get the resource Id. example) import com.myappdomain.R (USE YOUR NAMESPACE HERE) Then to get the actual string context.getString(R.string.SOME_STRING) – Roy Hinkley Oct 02 '12 at 21:02
  • 1
    @AndroidAddict +1 for you, you save me a headache! – Paranoid Android Oct 22 '12 at 11:01
17

You can pass the context of the Activity class to the java class and access the resources.

From your Activity Class

 Helper helper = new Helper(this);

Your Java class

public class Helper {

    Helper(Context c){
        c.getString(R.string.address);
    }
}
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
13

You can create a static Application Context in your custom Application class

public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext(){
        return mContext;
    }
}

Then you just need to call App.getContext().getResources() to get any resource values.

Just remember that this Context is Application type, so there are things that this Context is not good to use. Read this for further info.

Dark Leonhart
  • 1,494
  • 2
  • 13
  • 21
  • Android Studio complains about memory leaks for Context objects in static fields - would you do this differently now? – ATJ Jun 01 '20 at 11:46
-1

You could done if you add this line:

// this is the object itself, and idString is the ID String bound to the literal.
this.getString(R.string.idString)

I hope this comment helps you!

Brs.

Daan van Hulst
  • 1,426
  • 15
  • 32