【发布时间】:2019-01-25 11:15:55
【问题描述】:
我试图从我之前的帖子中的 URL 开始 XML 解析:Parsing XML on Android
因此,我尝试使用 InputStream 获取 XML 文件并使用 DocumentBuilder 解析其中的文本。
我试图使用 SharedPreferences 离线存储我的 XML 文件。
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string>
<name>username</name>
<value>mium</value>
</string>
这是我的 XML 文件。
private boolean parseXML(String target){
cache_string = getSharedPreferences("cache_userfiles", Context.MODE_PRIVATE);
cache_string_editor = cache_string.edit();
cache_string_editor.apply();
try {
URL url = new URL(target);
InputStream inputStream = url.openStream();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(inputStream);
Element element = document.getDocumentElement();
element.normalize();
NodeList nodeList = document.getElementsByTagName("string");
for (int current=0; current < nodeList.getLength(); current++){
Node node = nodeList.item(current);
if (node.getNodeType() == Node.ELEMENT_NODE){
Element element_specific = (Element) node;
cache_string_editor.putString(getValue("name", element_specific), getValue("value", element_specific));
cache_string_editor.apply();
}
}
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
这是我的解析代码。
为了使用这段代码,在我的主线程中,我使用了:
if (parseXML("http://www.myserver.com/file.xml")){
Log.d(TAG, "Success");
}
但是,我不断收到 android.os.NetworkOnMainThreadException。 我尝试添加线程和处理程序,但它一直给我一个错误。 有什么问题?我知道它无法处理主线程上的网络进程,但我不知道如何解决这个问题。
【问题讨论】:
标签: android xml parsing networkonmainthread