views:

1771

answers:

2

I am buiding an Android app, and I have a problem to get resource from string.xml. I need to have an 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 ?

+5  A: 

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.

Dave Webb
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) ?
Luc
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. http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html
Dave Webb
Thanks, that's a good point and a very good article. Cheers, Luc
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
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`.
Dave Webb
A: 

Do you ever refer this page: http://developer.android.com/intl/de/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.

XC
Thanks a lot, this is what I am using. Regards, Luc
Luc