android: how to load xml file from assets directory?

freeaks picture freeaks · Apr 5, 2011 · Viewed 40.4k times · Source

i have trouble loading an xml file from assets directory. using the same line of code (just changing the path) i get different results ( either ok or NPE / file corrupted ) the file "castle1.tmx" (it's an xml file) is copied in two locations:

  • res/xml/castle1.tmx
  • assets/level/castle1.tmx

with this line, it works:

XmlResourceParser xrp = ctx.getAssets().openXmlResourceParser("res/xml/castle1.tmx");

while with this line it doesn't:

XmlResourceParser xrp = ctx.getAssets().openXmlResourceParser("assets/level/castle1.tmx");

i get the following result:

04-05 21:46:40.940: WARN/ResourceType(29056): Bad XML block: header size 28024 or total size 1702240364 is larger than data size 70441
04-05 21:46:40.940: ERROR/TestParser(29056): Unable to read resource file
04-05 21:46:40.940: WARN/System.err(29056): java.io.FileNotFoundException: Corrupt XML binary file
04-05 21:46:40.940: WARN/System.err(29056):     at android.content.res.AssetManager.openXmlAssetNative(Native Method)
04-05 21:46:40.944: WARN/System.err(29056):     at android.content.res.AssetManager.openXmlBlockAsset(AssetManager.java:485)
04-05 21:46:40.944: WARN/System.err(29056):     at android.content.res.AssetManager.openXmlResourceParser(AssetManager.java:453)
04-05 21:46:40.944: WARN/System.err(29056):     at android.content.res.AssetManager.openXmlResourceParser(AssetManager.java:442)
04-05 21:46:40.944: WARN/System.err(29056):     at game.test.MapLoader.<init>(MapLoader.java:73)

file is found in both case... it's just that i cannot seem to be able to read it from asset dir using that method..

any ideas how can i load my xml file from assets directory ?

tnx

Answer

GrAnd picture GrAnd · Apr 5, 2011

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.