backslashN
backslashN

Reputation: 2875

how to access a java variable in strings.xml

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.

Upvotes: 3

Views: 6371

Answers (3)

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);

Upvotes: 0

Kamlakar Kate
Kamlakar Kate

Reputation: 397

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

Upvotes: 2

Pratik Popat
Pratik Popat

Reputation: 2999

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));

Upvotes: 7

Related Questions