简体   繁体   中英

how to get string values out of strings.xml and in to an arraylist [android]

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.

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

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

You can try this :

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

string1 is a string constant in strings.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM