6

I am building an Android app, and I have a problem to get resource from string.xml.

I need to have a URL in String.xml that will be used several times through the app.

I tried Resources.getText("my_url"), but this does not work. Eclipse complains when I use this.

Do you think this is the best way to do ?

2 Answers 2

12

What you probably want is:

String myUrl = getString(R.string.my_url); 

The getString() method is in Context which means that it's available directly in your Activity class since Activity is a subclass of Context. (The getString() method is also in Resources but it's easier to call on it directly on your Activity.)

What happens with your XML resources is that each is given a unique integer ID and this is added to the automatically generated R class as a public static final int. You then use these IDs to reference the resources. Have a look in the gen folder in your Eclipse project and you'll find the R class in there.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I'll check this. But, If I want to get this string outside an Activity (in a helper classe for instance), can I use a GetBaseContext().getString(key) ?
I have no idea what GetBaseContext() is I'm afraid. I pass a Context to each of my help classes to allow them to do things like this. However, be careful when you to this as if you hang on to a reference to the Context you can leak memory rather badly. android-developers.blogspot.com/2009/01/…
Thanks, that's a good point and a very good article. Cheers, Luc
Hello, I do not have any complain from eclipse when I use: server = context.getString(R.string.server_url); So, this seems good. The problem I might have is linked to the leak for context ref (as you pointed out in the article). Do you think this is safe to have a private context in an activity (instantiate with context = this in the onCreate method) and pass this context to the Utilities methods ? Thanks a lot, Luc
Passing the Context to the Utility methods is fine, just make sure none of the Utility classes hold on to a reference to the Content.
0

Do you ever refer this page: https://developer.android.com/guide/topics/resources/available-resources.html ?

If you want to retrieve the String represented by a resource ID, you can call the Context.getString() method.

Or, you have to post Eclipse's complains.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.