android - Android XML 解析错误
问题描述
我试图通过我之前的帖子从 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。我尝试添加线程和处理程序,但它一直给我一个错误。有什么问题?我知道它无法在主线程上处理网络进程,但我不知道如何解决这个问题。
解决方案
您不能在主线程上使用网络,因为它会阻塞 UI 组件。您需要为此使用 AsyncTask 。
new AsyncTask<Void ,Void ,Boolean>(){
@Override
protected Boolean doInBackground(Void... voids) {
return parseXML("http://www.myserver.com/file.xml");
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
Log.d(TAG, "Success "+aBoolean);
}
}.execute();
推荐阅读
- javascript - 用于不同类型标记的多个 for 循环 - 只有第一个循环有效
- r - 在 VennDiagram 中将标签强制向左
- python-3.x - tkinter 窗口在简单脚本上冻结(没有线程或其他)
- marklogic - QueryBatcher JobReport 错误失败号
- html - 如何在需要时(而不是定期)将服务器发送的事件通知发送到特定的浏览器会话?
- c# - 使用登录屏幕自动登录
- tensorflow - 将 Keras/TF/PyTorch 层分配给硬件类型
- python-3.x - 如何在 RHEL 上为 Python 3.7 安装 pip
- python - 我将如何继续我的小型赌场游戏?
- go - 如何使用 gogo/protobuf 获取自定义 go 类型