我在使用库JDOM2(准确地说是2.0.5)解析Android应用程序中的XML文件时遇到了问题。
在Java项目中,它工作正常,但在Android应用程序项目中,我收到以下消息:“无法打开http://jeancdc.perso.sfr.fr/fichierXML.xml”
这是我的XMLReader类:
package fr.jcdc.exemple.jdom;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import android.util.Log;
public class XMLReader {
public XMLReader() {
super();
}
public void loading() {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build("http://jeancdc.perso.sfr.fr/fichierXML.xml");
Element rootNode = document.getRootElement();
List<Element> charactersList = rootNode.getChildren("personnage");
for (int i = 0; i < charactersList.size(); i++) {
Element node = (Element) charactersList.get(i);
Log.d("tag", node.getChildText("prenom") + " " + node.getChildText("nom"));
}
}
catch (IOException ioex) {
Log.d("ioex", ioex.getMessage());
}
catch (JDOMException jdomex) {
Log.d("jdomex", jdomex.getMessage());
}
}
}
我的主要班级:
package fr.jcdc.exemple.jdom;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
private XMLReader xmlReader = new XMLReader();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xmlReader.loading();
}
}
这是我在日志中获得的异常跟踪的一部分:
06-24 22:58:39.794: D/ioex(18560): Couldn't open http://jeancdc.perso.sfr.fr/fichierXML.xml
06-24 22:58:39.794: W/System.err(18560): java.io.IOException: Couldn't open http://jeancdc.perso.sfr.fr/fichierXML.xml
06-24 22:58:39.864: W/System.err(18560): at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
06-24 22:58:39.864: W/System.err(18560): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
06-24 22:58:39.864: W/System.err(18560): at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:217)
06-24 22:58:39.864: W/System.err(18560): at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:277)
06-24 22:58:39.864: W/System.err(18560): at org.jdom2.input.SAXBuilder.build(SAXBuilder.java:1141)
.....
06-24 22:58:39.864: W/System.err(18560): Caused by: android.os.NetworkOnMainThreadException
06-24 22:58:39.872: W/System.err(18560): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
06-24 22:58:39.872: W/System.err(18560): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-24 22:58:39.872: W/System.err(18560): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-24 22:58:39.880: W/System.err(18560): ... 20 more
答案 0 :(得分:1)
最后评论有很多帮助。查看NetworkOnMainThreadException
的Google搜索结果不再允许您从应用程序的主线程访问网络。使用回调创建子线程以加载XML
答案 1 :(得分:0)
尝试传递URL而不是传递String。
java.net.URL temp;
try {
temp = new java.net.URL("http://jeancdc.perso.sfr.fr/fichierXML.xml");
} catch (java.net.MalformedURLException e) {
temp = null;
}
Document document = (Document) builder.build(temp);