5

I would like to get the correct way of parsing custom android tags with an XmlResourceParser. I am using Eclipse 3.6 with the android plug-in, and I would like some attributes like the name be expanded with the full string from strings.xml.

Here is the index.xml which is being parsed in the res/xml/ folder.

<?xml version="1.0" encoding="utf-8"?>
<Index xmlns:android="http://schemas.android.com/apk/res/android">
<Sheet
    shortName="o_2sq"
    android:name="@string/o_2sq"
    instructions=""
/>
</Index>

Here is the file strings.xml in the res/values/ folder

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="o_2sq">Organize two squares</string>
</resources>

and the code fragment that parses the first index.xml with an XmlResourceParser:

String name = xpp.getAttributeValue(null, "android:name");
String shortName = xpp.getAttributeValue(null, "shortName");

The variable name contains null, but shortName contains "o_2sq". I also tried the following without success:

String name = xpp.getAttributeValue("android", "name");

What is the correct way of writing the sentence so that the variable name would contain "Organize two squares" ?

3 Answers 3

5

Try this:

String name = xpp.getAttributeValue("http://schemas.android.com/apk/res/android", "name");
Sign up to request clarification or add additional context in comments.

2 Comments

Nice try. It gives something better : my variable name now contains the string "@2131099651". Not sure why.
It is probably string resource ID. Try to use getString( number ); method to get string.
2
final String NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android";
final int VALUE_NOT_SET = -1;
int resId = parser.getAttributeResourceValue(NAMESPACE_ANDROID, "name", VALUE_NOT_SET);
String value = null;
if (VALUE_NOT_SET != resId) {
    value = context.getString(resId);
}

I think the above code could help you.

Comments

1

Best solution I found to overcome that problem.

String s = xpp.getAttributeValue("http://schemas.android.com/apk/res/android", "name");
String name = null;
if(s != null && s.length() > 1 && s.charAt(0) == '@') {
  int id = Integer.parseInt(s.substring(1));
  name = getString(id);
} else {
  name = "";
}

2 Comments

Did you mean else { name = s' } ? Seems like that would allow that attribute to be either a resource or a hard-coded string, no?
I needed name to be not null in my case. This is why.

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.