android: how to load xml file from assets directory?

时光毁灭记忆、已成空白 提交于 2019-11-27 13:15:57

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).

Have a look at

https://github.com/pilhuhn/TurtleCar/blob/master/src/de/bsd/turtlecar/Board.java#L30 which is called from https://github.com/pilhuhn/TurtleCar/blob/master/src/de/bsd/turtlecar/SampleView.java#L45

for an example.

Basically you need to ask the AssetManager for the file:

 AssetManager assetManager = context.getAssets();
    try {
        InputStream is = assetManager.open("1.xml");
       ....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!