1

Pretty much I've been trying to figure this out for the past hour.
I want to generically get strings from strings.xml and in to my code so I can dynamically change the amount of strings without having to change anything in my code that loads them in to the array list.

So far all I have is

for(Field x :R.string.class.getFields())
        if(x.getName().startsWith("ans"))
            choices.add(/*what do I add here to get the string value from the field in to the arraylist */);

I can not figure out for the life of me how to get the string value out of the field object. All I am getting is either Id's [or at least what I think is an Id] or the name I've assigned it inside the strings.xml file.

3 Answers 3

4
    Resources res = getResources();
    for(Field x :R.string.class.getFields())
        if(x.getName().startsWith("ans")){
                int id = x.get(null);
                choices.add(res.getString(id));
            }
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah just had to change x.get(null) and cast it as an integer and surround with a try,catch But it is the correct solution I was yearning for.
try {choices.add(res.getString((Integer) x.get(null))); } //this gets the id and then grabs the resource associated catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e){ e.printStackTrace();} }
1

Create an XML file example.xml in res/xml folder

<?xml version="1.0" encoding="utf-8"?>
<data>
    <record name="foo" />
</data>

then parse it as shown below

XmlResourceParser xrp = context.getResources().getXml(R.xml.example);
try {
  int eventType = xrp.next();
  while (eventType != XmlPullParser.END_DOCUMENT) {
    if (eventType == XmlPullParser.START_TAG && xrp.getName().equalsIgnoreCase("record")) {

      String name = xrp.getAttributeValue(null, "name");

      //choices.add(name);
    }

    eventType = xrp.next();
  }
} catch (XmlPullParserException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

1 Comment

This is way too much effort. I wanted to use reflection. Faylons answer is the correct solution for my needs.
0

You can try this :

 choices.add(getResources().getString(R.string.string1));

string1 is a string constant in strings.xml

1 Comment

Not generic enough. I want to add from a loop, not from a bunch of add() statements with the ID's hardcoded in, it causes maintenance issues.

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.