首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NetworkOnMainThread

NetworkOnMainThread
EN

Stack Overflow用户
提问于 2012-03-17 07:38:46
回答 3查看 6.6K关注 0票数 8

当我尝试实现以下代码时,我得到了一个NetworkOnMainThreadException:

代码语言:javascript
复制
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);
        }
}

和操控者:

代码语言:javascript
复制
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 "";
  }    

}

知道为什么吗?它应该可以工作,我读过的所有教程都将其视为工作代码,但它不会运行,只会抛出异常。我读过,我可能需要实现异步任务,但我是新手,不确定哪些部分需要自己的线程。感谢您的帮助、批评(建设性的)、建议等。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-17 07:41:42

知道为什么吗?

因为,如果这段代码是在主应用程序线程上执行的,那么您就是在主应用程序线程上执行网络I/O。

我读到过,我可能需要实现异步任务,但我是新手,不确定哪些部分需要自己的线程。

我会将网络I/O和解析放在doInBackground()中,将setListAdapter()调用放在AsyncTaskonPostExecute()中。

票数 10
EN

Stack Overflow用户

发布于 2012-03-17 10:10:43

如果您只是想测试您的代码,并且不想添加更多的复杂性,那么可以将以下代码添加到您的onCreate()

代码语言:javascript
复制
if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
}

你不会希望这是永久性的,因为UI线程上的网络操作在使用应用程序时会带来糟糕的体验,但在测试时可能会很有用。

票数 3
EN

Stack Overflow用户

发布于 2012-03-17 09:11:00

除了CommonsWare answer,NetworkOnMainThreadException是在2.3.3 (Gingerbread_MR1)和3.0 (蜂窝)之间的某个时候添加的。如果你看一下

代码语言:javascript
复制
android.app.ActivityThread

你会发现下面这段代码:

代码语言:javascript
复制
    /**
     * For apps targetting SDK Honeycomb or later, we don't allow
     * network usage on the main event loop / UI thread.
     *
     * Note to those grepping:  this is what ultimately throws
     * NetworkOnMainThreadException ...
     */
    if (data.appInfo.targetSdkVersion > 9) {
        StrictMode.enableDeathOnNetwork();
    }

我认为您遵循的教程是在这篇文章放到适当位置之前编写的,因此没有导致NetworkOnMainThreadException。遵循有关AsyncTask的CommonsWare说明,您就可以修复您的错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9745859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档