问题描述
当我尝试实现以下代码时收到 NetworkOnMainThreadException:
I get a NetworkOnMainThreadException when I try to implement the following code:
public class HandlingXMLStuff extends ListActivity{
static final String URL = "xml_file";
static final String ITEM = "item"; //parent
static final String Id = "id";
static final String Name = "name";
static final String Desc = "desc";
static final String Link = "Link";
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.xmllist);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
xmlparser parser = new xmlparser();
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(ITEM);
//START: loop through all item nodes <item>
for (int i = 0;i<nl.getLength();i++){
//lets create our HASHMAP!! (feeds items into our ArrayList)
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add each child node to the HashMap (key, value/<String, String>)
map.put(Name, parser.getValue(e, Name));
map.put(Desc, parser.getValue(e, Desc));
map.put(Link, parser.getValue(e, Link));
menuItems.add(map);
}//DONE
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[] {Name, Desc, Link}, new int []{R.id.name, R.id.description, R.id.link});
setListAdapter(adapter);
}
}
和处理程序:
public class xmlparser{
public String getXmlFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}
知道为什么吗?它应该可以工作,我读过的所有教程都将其视为工作代码,但它不会运行,只会引发异常.我读过我可能需要实现 asynctask 但我不熟悉它并且不确定哪些部分需要他们自己的线程.感谢您的任何帮助、批评(建设性)、建议等.
Any idea why? It should work, all the tutorials I've read treat this as working code but it doesn't run and only throws the exception. I've read I might need to implement asynctask but im new to it and not sure what parts need their own thread. Thanks for any help, critique (constructive), suggestions, etc.
推荐答案
因为,如果那段代码正在主应用程序线程上执行,那么您就是在主应用程序线程上进行网络 I/O.
Because, if that hunk of code is being executed on the main application thread, you are doing network I/O on the main application thread.
我读过我可能需要实现 asynctask 但我不熟悉它并且不确定哪些部分需要他们自己的线程.
我会将网络 I/O 和解析放在 doInBackground()
中,并将 setListAdapter()
调用放在 onPostExecute()
中一个 AsyncTask
.
I would put the network I/O and the parsing in doInBackground()
and the setListAdapter()
call in onPostExecute()
of an AsyncTask
.
这篇关于主线程网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!