NetworkOnMainThread [英] NetworkOnMainThread

查看:94
本文介绍了NetworkOnMainThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个NetworkOnMainThreadException当我尝试实施下列code:

 公共类HandlingXMLStuff扩展ListActivity {
静态最终字符串URL =xml_file;

 静态最后弦乐ITEM =项目; //父
    静态最后字符串ID =ID;
    静态最终字符串名称=名称;
    静态最后弦乐说明=递减;
    静态最终字符串链接=联系;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.xmllist);

ArrayList的< HashMap的<字符串,字符串>>菜单项=新的ArrayList< HashMap的<字符串,字符串>>();

XMLParser的分析器=新XMLParser的();
XML字符串= parser.getXmlFromUrl(URL);
文档DOC = parser.getDomElement(XML);


NodeList的NL = doc.getElementsByTagName(ITEM);


//开始:遍历所有项目节点<项目>
的for(int i = 0; I< nl.getLength();我++){
    //让我们创建我们的HASHMAP! (供稿物品进入我们的ArrayList)
    HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
    元素e =(元)nl.item(我);
    //添加每个子节点的HashMap的(键,值/<字符串,字符串>)
    map.put(名称,parser.getValue(即名称));
    map.put(说明,parser.getValue(即说明));
    map.put(链接,parser.getValue(即链接));


    menuItems.add(图)

} // DONE


ListAdapter适配器=新SimpleAdapter(这一点,菜单项,R.layout.list_item,
        新的String [] {名,说明,链接},新的INT [] {R.id.name,R.id.description,R.id.link});

setListAdapter(适配器);
        }
}
 

和处理程序:

 公共XMLParser类{

公共字符串getXmlFromUrl(字符串URL){
XML字符串= NULL;

尝试 {

    DefaultHttpClient的HttpClient =新DefaultHttpClient();
    HttpPost httpPost =新HttpPost(URL);

    HTT presponse HTT presponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = HTT presponse.getEntity();
    XML = EntityUtils.toString(httpEntity);

}赶上(UnsupportedEncodingException E){
    e.printStackTrace();
}赶上(ClientProtocolException E){
    e.printStackTrace();
}赶上(IOException异常E){
    e.printStackTrace();
}

返回XML;
}
公开文件getDomElement(XML字符串){
    文档DOC = NULL;
    DocumentBuilderFactory的DBF = DocumentBuilderFactory.newInstance();
    尝试 {

        DocumentBuilder的DB = dbf.newDocumentBuilder();

        InputSource的是=新的InputSource();
            is.setCharacterStream(新StringReader(XML));
            DOC = db.parse(是);

        }赶上(的ParserConfigurationException E){
            Log.e(错误,e.getMessage());
            返回null;
        }赶上(的SAXException E){
            Log.e(错误,e.getMessage());
            返回null;
        }赶上(IOException异常E){
            Log.e(错误,e.getMessage());
            返回null;
        }

        返回文档;
  }

公共字符串的getValue(元素项,字符串str){
        节点列表N = item.getElementsByTagName(STR);
        返回this.getElementValue(n.item(0));
    }

公共最后弦乐getElementValue(节点ELEM){
         子节点;
         如果(ELEM!= NULL){
             如果(elem.hasChildNodes()){
                 对于(子= elem.getFirstChild();!孩子= NULL;孩子= child.getNextSibling()){
                     如果(child.getNodeType()== Node.TEXT_NODE){
                         返回child.getNodeValue();
                     }
                 }
             }
         }
         返回 ;
  }
 

}

任何想法,为什么?它应该工作,所有我读过把这个作为工作code中的教程,但它并没有跑,只抛出异常。我读过,我可能需要实现的AsyncTask,但即时通讯新的它并不能确定哪些部分需要自己的线程。感谢您的帮助,批评(建设性),建议等。

解决方案
  

任何想法,为什么?

由于,如果code表示猛男被主应用程序线程上执行,你正在做的网络I / O的主应用程序线程上。

  

我读过,我可能需要实现的AsyncTask,但即时通讯新的它并不能确定哪些部分需要自己的线程。

我把网络I / O和解析doInBackground() setListAdapter()通话在 onPostExecute()的AsyncTask

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);
        }
}

and the handler:

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 "";
  }    

}

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.

解决方案

Any idea why?

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.

I've read I might need to implement asynctask but im new to it and not sure what parts need their own thread.

I would put the network I/O and the parsing in doInBackground() and the setListAdapter() call in onPostExecute() of an AsyncTask.

这篇关于NetworkOnMainThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆