0

嗨,我正在练习从 XML 中获取价值。
我从教程中复制它,但我总是进入捕获区并将文本设置为空。
这是代码:
MainActivity.java

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);

            /* Create a new TextView to display the parsingresult later. */
            TextView tv = new TextView(this);
            try {
                    /* Create a URL we want to load some xml-data from. */
                    URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");

                    /* Get a SAXParser from the SAXPArserFactory. */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();

                    /* Get the XMLReader of the SAXParser we created. */
                    XMLReader xr = sp.getXMLReader();
                    /* Create a new ContentHandler and apply it to the XML-Reader*/
                    ExampleHandler myExampleHandler = new ExampleHandler();
                    xr.setContentHandler(myExampleHandler);

                    /* Parse the xml-data from our URL. */
                    xr.parse(new InputSource(url.openStream()));
                    /* Parsing has finished. */

                    /* Our ExampleHandler now provides the parsed data to us. */
                    ParsedExampleDataSet parsedExampleDataSet =
                                                                    myExampleHandler.getParsedData();

                    /* Set the result to be displayed in our GUI. */
                    tv.setText(parsedExampleDataSet.toString());

            } catch (Exception e) {
                    /* Display any Error to the GUI. */
                    tv.setText("Error: " + e.getMessage());
            }
            /* Display the TextView. */
            this.setContentView(tv);
    }

}

这是 Logcat:

11-13 12:02:40.689: W/System.err(1061): android.os.NetworkOnMainThreadException
11-13 12:02:40.749: W/System.err(1061):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-13 12:02:40.789: W/System.err(1061):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-13 12:02:40.789: W/System.err(1061):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-13 12:02:40.809: W/System.err(1061):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-13 12:02:40.859: W/System.err(1061):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-13 12:02:40.859: W/System.err(1061):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-13 12:02:40.879: W/System.err(1061):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
11-13 12:02:40.879: W/System.err(1061):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-13 12:02:40.952: W/System.err(1061):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-13 12:02:40.952: W/System.err(1061):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-13 12:02:40.959: W/System.err(1061):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-13 12:02:40.959: W/System.err(1061):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-13 12:02:41.009: W/System.err(1061):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-13 12:02:41.029: W/System.err(1061):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
11-13 12:02:41.029: W/System.err(1061):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
11-13 12:02:41.029: W/System.err(1061):     at java.net.URL.openStream(URL.java:462)
11-13 12:02:41.099: W/System.err(1061):     at com.example.xmltestfinal1_1.MainActivity.onCreate(MainActivity.java:38)
11-13 12:02:41.099: W/System.err(1061):     at android.app.Activity.performCreate(Activity.java:5008)
11-13 12:02:41.152: W/System.err(1061):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-13 12:02:41.179: W/System.err(1061):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-13 12:02:41.179: W/System.err(1061):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 12:02:41.239: W/System.err(1061):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 12:02:41.289: W/System.err(1061):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 12:02:41.289: W/System.err(1061):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 12:02:41.299: W/System.err(1061):     at android.os.Looper.loop(Looper.java:137)
11-13 12:02:41.359: W/System.err(1061):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 12:02:41.359: W/System.err(1061):     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 12:02:41.399: W/System.err(1061):     at java.lang.reflect.Method.invoke(Method.java:511)
11-13 12:02:41.409: W/System.err(1061):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 12:02:41.442: W/System.err(1061):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 12:02:41.449: W/System.err(1061):     at dalvik.system.NativeStart.main(Native Method)
4

3 回答 3

1

在这条线上

xr.parse(new InputSource(url.openStream()));

您正在主线程中执行网络操作

长操作应该在后台线程中执行,如下所示

  1. 网络操作(下载文件等)
  2. 文件操作(读取文件内容等)
  3. 复杂的计算...

为了实现这一点。你应该使用AsyncTask

您可以在onPostExecute()

额外的,

如果要从后台线程中设置 UI 对象中的数据,请使用Handler对象

于 2012-11-13T04:31:15.333 回答
1

您正在从应用的主 (UI) 线程访问网络,这在最新版本的 Android 中是不允许的。这就是NetworkOnMainThreadExceptionLogcat 输出中出现的原因。如果网络速度较慢,您的用户可能会看到“应用程序无响应”警告,您的应用程序可能会因此被终止。

您需要使用AsyncTask在后台线程中下载和解析您的 XML 线程。这使您的应用程序能够在后台线程处理 XML 数据时与用户进行交互。如果您需要更多详细信息,有很多AsyncTask关于 SO 的教程可以提供帮助。

于 2012-11-13T04:17:56.970 回答
0

` 公共无效 demoxml()

{ 
    AssetManager manager = getAssets();
    InputStream stream;

    try {
        XMLDOMParser parser = new XMLDOMParser();
        stream = manager.open("game.xml");
        Document doc = parser.getDocument(stream);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Log.i("DocumentBuilder--->", "Document Building is complete--> ready for parsing");

       // Document doc = dBuilder.parse("http://myinfo.comuf.com/ram/game.xml");
        doc.getDocumentElement().normalize();

        Log.i("Document--('-')->","it is open");

        //get all tabs
        NodeList nodeList=doc.getElementsByTagName("string");
        int lengthq = nodeList.getLength();
        Log.i("Node length is ", ""+String.valueOf(lengthq));
        NodeList nl = doc.getElementsByTagName("array");
        int length = nl.getLength();
        Log.i("Node length is ", ""+String.valueOf(length));

        for(int i=0; i<length; i++ ){
            Node currentNode = nl.item(i);
           // RSSItem item = new RSSItem();

            Log.i("Main Node-->"+i+"---",currentNode.toString());

            NodeList nchild = currentNode.getChildNodes();
            int clength = nchild.getLength();

            //get the required element from each item
            for(int j=1;  j<clength; j=j+2){

                Node thisNode = nchild.item(j);

                String theString;
                String nodeName = thisNode.getNodeName();
                theString = nchild.item(j).getFirstChild().getNodeValue();

                Log.i("('-')ChildNode--->"+nodeName+"="+j+"---",theString.toString());
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}`
于 2016-04-04T12:42:59.953 回答