试图从url获取xml但得到FATAL ERROR:main

时间:2014-01-01 04:38:08

标签: java android xml fatal-error

我是android和java的初学者编程所以请原谅我,如果代码是错误的。我只是想从一个url中获取一些xml,然后在logcat中显示它,但我一直得到同样的错误。

这是日志:

01-01 19:49:38.065: E/Trace(6471): error opening trace file: No such file or directory (2)
01-01 19:49:38.225: D/AndroidRuntime(6471): Shutting down VM
01-01 19:49:38.225: W/dalvikvm(6471): threadid=1: thread exiting with uncaught exception (group=0x40c72300)
01-01 19:49:38.795: E/AndroidRuntime(6471): FATAL EXCEPTION: main
01-01 19:49:38.795: E/AndroidRuntime(6471): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.alexisdelatorre.helloxml/com.alexisdelatorre.helloxml.MainActivity}: android.os.NetworkOnMainThreadException
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.os.Looper.loop(Looper.java:137)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.ActivityThread.main(ActivityThread.java:4745)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at java.lang.reflect.Method.invokeNative(Native Method)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at java.lang.reflect.Method.invoke(Method.java:511)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at dalvik.system.NativeStart.main(Native Method)
01-01 19:49:38.795: E/AndroidRuntime(6471): Caused by: android.os.NetworkOnMainThreadException
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at com.alexisdelatorre.helloxml.JavaXmlTutorial.getXmlFromUrl(JavaXmlTutorial.java:64)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at com.alexisdelatorre.helloxml.JavaXmlTutorial.<init>(JavaXmlTutorial.java:31)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at com.alexisdelatorre.helloxml.MainActivity.onCreate(MainActivity.java:21)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.Activity.performCreate(Activity.java:5008)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-01 19:49:38.795: E/AndroidRuntime(6471):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-01 19:49:38.795: E/AndroidRuntime(6471):     ... 11 more

代码:

package com.alexisdelatorre.helloxml;

import java.io.IOException;

public class JavaXmlTutorial {

    public JavaXmlTutorial() throws XmlPullParserException, IOException{


        String xmlFromUrl = getXmlFromUrl("http://api.androidhive.info/pizza/?format=xml");

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();

        xpp.setInput(new StringReader (xmlFromUrl));
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
         if(eventType == XmlPullParser.START_DOCUMENT) {
             Log.d(TAGS.DEBUG, "start document");
         } else if(eventType == XmlPullParser.END_DOCUMENT) {
             Log.d(TAGS.DEBUG, "end document");
         } else if(eventType == XmlPullParser.START_TAG) {
             Log.d(TAGS.DEBUG,"Start tag "+xpp.getName());
         } else if(eventType == XmlPullParser.END_TAG) {
             Log.d(TAGS.DEBUG,"End tag "+xpp.getName());
         } else if(eventType == XmlPullParser.TEXT) {
             Log.d(TAGS.DEBUG,"Text "+xpp.getText());
         }
         eventType = xpp.next();
        }

    }

    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            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
        return xml;
    }


}

1 个答案:

答案 0 :(得分:0)

您无法在主线程上发出HTTP个请求,这会导致UI冻结。所以它会引发NetworkOnMainThreadException异常。您需要在AsyncTask或其他Thread中执行此操作。

查看NetworkOnMainThreadException

class SynchTask extends AsyncTask<Void,Void,Void>
{
          protected void onPreExecute()
          {           super.onPreExecute();
                    //display progressdialog.
          } 

           protected void doInBackground(Void ...params)
          {  
                //http request. do not update ui here
                  JavaXmlTutorial parse=new JavaXmlTutorial();
                 return null;
          } 
          protected void onPostExecute(Void result)
          {     
                    super.onPostExecute(result);
                    //dismiss progressdialog.
                    //update ui
          } 
}