android: how to load xml file from assets directory?

In res/ folder all xml files are precompiled, whereas in assets/ folder they are not. So, you can’t use openXmlResourceParser() with non-precompiled resources. Instead use open() and read file through InputStream.

i succeded at loading and parsing my xml file from assets directory (assets/level/castle1.tmx)

here’s what i did:

replaced this:

  XmlResourceParser xrp = ctx.getResources().getXml(ctx.getResources().getIdentifier(name, "xml", ctx.getPackageName()));

by this:

  InputStream istr = context.getAssets().open("level/"+name+".tmx");
  XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
  factory.setNamespaceAware(true); 
  xrp = factory.newPullParser(); 
  xrp.setInput(istr, "UTF-8");  

then all i had to do was editing some getAttributeIntValue() lines:

  int a = xrp.getAttributeIntValue(null, "width",0));

into this:

  int a = Integer.parseInt(xrp.getAttributeValue(null, "width"));

and all the rest worked without modifications 🙂
..this class is for parsing tiled xml/map files to build my game levels.
before, it worked using res/ but i wanted to try to put all my files into assets/ instead.
so now it works 🙂

thanks for the help

The reason is because you are trying to load a binary XML file (your error is java.io.FileNotFoundException: Corrupt XML binary file).

All of the Android XML files (layouts, strings etc) stored in res are automatically compiled to binary XML when your project is compiled. XML files in assets are treated as standard XML files and so are not compiled to binary XML.

In summary: Android XML files must be in the res folder. You can only store plain-text XML in the assets folder (not layout files and such-like).