2013-07-23 83 views
-5

我的XML解析器不想顯示.. 這是我的代碼,XML解析器NetworkOnMainThreadException(再次)

public class XMLParser { 
    public XMLParser(){ 

    } 
    public String getXmlFromUrl (String url){ 
     String xml = null; 
     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpGet httpPost = new HttpGet(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) { 
      // TODO: handle exception 
      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 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 ""; 

    } 
    public String getValue (Element item, String str){ 
     NodeList n = item.getElementsByTagName(str); 
     return this.getElementValue(n.item(0)); 

    } 

} 

,這是我的主要

public class MainActivity extends ListActivity { 
    static final String URL = "http://api.androidhive.info/pizza/?format=xml"; 
    // XML node keys 
    static final String KEY_ITEM = "item"; // parent node 
    static final String KEY_ID = "id"; 
    static final String KEY_NAME = "name"; 
    static final String KEY_COST = "cost"; 
    static final String KEY_DESC = "description"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


    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(KEY_ITEM); 
    for (int i = 0; i < nl.getLength(); i++) { 
     HashMap<String, String> map = new HashMap<String, String>(); 
     Element e = (Element) nl.item(i); 
     map.put(KEY_ID, parser.getValue(e, KEY_ID)); 
     map.put(KEY_NAME, parser.getValue(e, KEY_NAME)); 
     map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST)); 
     map.put(KEY_DESC, parser.getValue(e, KEY_DESC)); 

     menuItems.add(map); 
    } 

    ListAdapter adapter = new SimpleAdapter(this, menuItems, 
      R.layout.list_item, 
      new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] { 
        R.id.name, R.id.desciption, R.id.cost }); 

    setListAdapter(adapter); 
    } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 

,這是錯誤

07-23 01:58:08.649: E/AndroidRuntime(1347): FATAL EXCEPTION: main 
07-23 01:58:08.649: E/AndroidRuntime(1347): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tr.tryjson/com.tr.tryjson.MainActivity}: android.os.NetworkOnMainThreadException 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.ActivityThread.access$600(ActivityThread.java:141) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.os.Handler.dispatchMessage(Handler.java:99) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.os.Looper.loop(Looper.java:137) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.ActivityThread.main(ActivityThread.java:5039) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at java.lang.reflect.Method.invokeNative(Native Method) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at java.lang.reflect.Method.invoke(Method.java:511) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at dalvik.system.NativeStart.main(Native Method) 
07-23 01:58:08.649: E/AndroidRuntime(1347): Caused by: android.os.NetworkOnMainThreadException 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at java.net.InetAddress.getAllByName(InetAddress.java:214) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at com.tr.tryjson.JsonParser.getJSONFromUrl(JsonParser.java:37) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at com.tr.tryjson.MainActivity.onCreate(MainActivity.java:48) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.Activity.performCreate(Activity.java:5104) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 
07-23 01:58:08.649: E/AndroidRuntime(1347):  ... 11 more 

請幫助我..

+1

1.閱讀你的logcat。 2. Google「NetworkOnMainThreadException」。 3.當你嘗試實現一個AsyncTask並且仍然失敗時回到這裏。 – 323go

回答

0

我認爲問題在於,自從最新版本的Android以來,您無法從主線程或UI線程打開互聯網連接,因爲這可以視爲阻止操作。您需要爲此創建單獨的線程,使用一個線程,一個的AsyncTask,一個裝載機...

的logcat的是你的朋友,剛讀輸出:

07-23 01:58:08.649: E/AndroidRuntime(1347): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tr.tryjson/com.tr.tryjson.MainActivity}: android.os.NetworkOnMainThreadException 


您可以參閱Post實施AsyncTAsk https://stackoverflow.com/a/6343299/588917

+0

對不起,但我沒有複製你的評論。我在寫評論時寫了我的答案。原諒我慢,並尋找一些鏈接,以改善我的答案,並給一個地方與代碼鏈接(我鏈接到源代替複製,你在說什麼我)。像你這樣的人,我看到人們不再回答問題.... – AitorTheRed