【问题标题】:NetworkOnMainThreadNetworkOnMainThread
【发布时间】:2012-04-02 12:04:49
【问题描述】:

当我尝试实现以下代码时收到 NetworkOnMainThreadException:

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 但我是新手,不确定哪些部分需要自己的线程。感谢您的任何帮助、批评(建设性)、建议等。

【问题讨论】:

标签: android parsing xml-parsing document


【解决方案1】:

知道为什么吗?

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

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

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

【讨论】:

    【解决方案2】:

    如果您只是想测试您的代码,并且不想增加任何复杂性,您可以将其添加到您的 onCreate()

    if (android.os.Build.VERSION.SDK_INT > 9) {
          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
    }
    

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

    【讨论】:

      【解决方案3】:

      添加到 CommonsWare 答案中,NetworkOnMainThreadException 是在 2.3.3 (Gingerbread_MR1) 和 3.0 (Honeycomb) 之间的某个时间添加的。如果你看

      android.app.ActivityThread
      

      你会发现下面这段代码:

          /**
           * 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。按照 CommonsWare 有关 AsyncTask 的说明,您将修复错误。

      【讨论】:

        猜你喜欢
        • 2013-03-17
        • 1970-01-01
        • 2016-01-20
        • 2012-04-06
        • 1970-01-01
        • 2016-08-07
        • 2017-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多