Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android custom XML parser fails to resolve android namespace

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" ?

like image 739
Mikaël Mayer Avatar asked Apr 12 '12 09:04

Mikaël Mayer


3 Answers

Try this:

String name = xpp.getAttributeValue("http://schemas.android.com/apk/res/android", "name");
like image 116
skywall Avatar answered Nov 08 '22 14:11

skywall


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 = "";
}
like image 1
Mikaël Mayer Avatar answered Nov 08 '22 13:11

Mikaël Mayer


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.

like image 1
androidyue Avatar answered Nov 08 '22 13:11

androidyue