NetworkOnMainThreadException(再次)

时间:2013-07-23 05:59:05

标签: android

我的xml解析器不想显示.. 这是我的代码xml解析器

    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 个答案:

答案 0 :(得分:0)

我认为问题在于,自Android的最新版本以来,您无法从主线程或UI线程打开Internet连接,因为这可以被视为阻止操作。您需要为此创建一个单独的线程,使用Thread,AsyncTask,Loader ...

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 


您可以阅读此文章以实现AsyncTAsk https://stackoverflow.com/a/6343299/588917