4

I've looked and tried many things but it seems my App isn't getting the values for strings in strings.xml. It actually seems like it's passing blank. I think there's an issue initializing.

strings.xml

    <string name="itb_cityID">2</string>
        <string name="itb_city">New York</string>

constants.java excerpt:

public class ConstantData {

public static String cityID="2";
public static String city="New York";

How do I set cityID = R.strings.itb_cityID and city=itb_city the correct way?

3 Answers 3

13

String yourString = Context.getResources().getString(R.string.your_string);

Note: You can't use Context statically. If you're inside an Activity, simply use this or call getResources() directly. Otherwise you'll need to obtain a handle to your application's context via getApplicationContext().

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

3 Comments

ok, so when I do this, String cityID = Context.getResources().getString(R.string.itb_cityID); I get a "Context cannot be resolved" and gives 8 options to fix Thanks for the quick reply!
Try using getApplicationContext() to retrieve the context.
what would my line look like using getResources or getApplicationContext?
9

This example could be useful

  • XML file saved at res/values/strings.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Hello!</string>
    </resources>
    
  • This layout XML applies a string to a View

    <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello" />
    
  • This application code retrieves a string:

    String string = getString(R.string.hello);

    You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.

This example is from http://developer.android.com/guide/topics/resources/string-resource.html

Comments

0

Have you checked that the entire project is error free. If it is not there may be an error that is preventing R.java from being updated with your string. You could try to "Clean" you projected from the "Project" menu. That may work. Also, I can't see why you would have to use Context., usually you should be able to call getResources(). directly (in some situations even this is unnecessary). A good thing to look for is if the string you have declared in your strings.xml file is recognised as a declared string.

Comments

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.