3

How can I access a static java variable in a resource in strings.xml in the android studio?

I have a variable like this:

public static final String NUM_OF_DAYS = "10";

Now, I want to use this somehow in strings.xml in a resource.

EDIT:

I just want to use the string.xml resource (which will access NUM_OF_DAYS) in a java file.

2
  • You can't access Java objects from a resource file. Commented Jun 30, 2017 at 9:57
  • 1
    @Rotwang I didn't know whether it is possible or not, which is why I asked the question in the first place. Aren't stack exchange sites supposed to be for that? Commented Jun 30, 2017 at 11:37

3 Answers 3

7

You can use your variable like this

public static final String NUM_OF_DAYS = "10";

string.xml

<string name="days">No of days: %s</string>

Java class

YOUR_VIEW.settext(getString(R.string.days, NUM_OF_DAYS));
Sign up to request clarification or add additional context in comments.

1 Comment

The OP asked the other way around: Given a variable in Java, he thinks he can access it from a resource file. Which is impossible.
2

Hey you can not do such thing we do not edit string.xml from java code

1 Comment

Not what the OP asked: Given a variable in Java, he thinks he can access it from a resource file. Which is impossible.
0

Because getString() is non-static you need a static Context for that.

In manifest file declare following

<application android:name="com.xyz.YourApplication">

</application>

Then wripte following class

public class YourApplication extends Application {
    private static Context context;

    public void onCreate() {
        super.onCreate();
        YourApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return YourApplication.context;
    }
}

Now you can use static context everywhere you need

      private static final String NUM_OF_DAYS = YouApplication.getAppContext()
.getString(R.string.yourString);

1 Comment

Not what the OP asked: Given a variable in Java, he thinks he can access it from a resource file. Which is impossible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.