Reputation: 348
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.
Upvotes: 1
Views: 2045
Reputation: 7450
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));
}
Upvotes: 4
Reputation: 768
You can try this :
choices.add(getResources().getString(R.string.string1));
string1 is a string constant in strings.xml
Upvotes: 0
Reputation: 454
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();
}
Upvotes: 1