NetworkOnMainThread

Я получаю исключение 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 "";
  }    

}

Есть идеи почему? Это должно работать, все учебники, которые я читал, рассматривают это как рабочий код, но он не запускается и только выдает исключение. Я читал, что мне может понадобиться реализовать асинхронную задачу, но я новичок в этом и не уверен, какие части нуждаются в собственном потоке. Спасибо за любую помощь, критику (конструктивную), предложения и т. д.

8
задан Bob 16 March 2012 в 23:38
поделиться