0

我想创建一个简单的 RSS 阅读器,这是我的实际代码:

    public class MainActivity extends ListActivity {

    List headlines;
    List links;

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

        // Initializing instance variables
        headlines = new ArrayList();
        links = new ArrayList();

        try {
            URL url = new URL(
                    "http://www.radiojudaicastrasbourg.fr/category/podcasts/linvite-de-la-redaction/feed/");

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

            // We will get the XML from an input stream
            xpp.setInput(getInputStream(url), "UTF_8");

            /*
             * We will parse the XML content looking for the "<title>" tag which
             * appears inside the "<item>" tag. However, we should take in
             * consideration that the rss feed name also is enclosed in a
             * "<title>" tag. As we know, every feed begins with these lines:
             * "<channel><title>Feed_Name</title>...." so we should skip the
             * "<title>" tag which is a child of "<channel>" tag, and take in
             * consideration only "<title>" tag which is a child of "<item>"
             * 
             * In order to achieve this, we will make use of a boolean variable.
             */
            boolean insideItem = false;

            // Returns the type of current event: START_TAG, END_TAG, etc..
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {

                    if (xpp.getName().equalsIgnoreCase("item")) {
                        insideItem = true;
                    } else if (xpp.getName().equalsIgnoreCase("title")) {
                        if (insideItem)
                            headlines.add(xpp.nextText()); // extract the
                                                            // headline
                    } else if (xpp.getName().equalsIgnoreCase("enclosure")) {
                        if (insideItem)
                            links.add(xpp.getAttributeValue(null, "url")); // extract
                                                                            // the
                                                                            // link
                                                                            // of
                                                                            // article
                    }
                } else if (eventType == XmlPullParser.END_TAG
                        && xpp.getName().equalsIgnoreCase("item")) {
                    insideItem = false;
                }

                eventType = xpp.next(); // move to next element
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Binding data
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, headlines);

        setListAdapter(adapter);

    }

    public InputStream getInputStream(URL url) {
        try {
            return url.openConnection().getInputStream();
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri uri = Uri.parse((String) links.get(position));
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
}

当我启动应用程序时,它会立即关闭,我不知道为什么。这是日志猫:

>09-12 17:09:06.065: E/AndroidRuntime(11394): FATAL EXCEPTION: main
09-12 17:09:06.065: E/AndroidRuntime(11394): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parserxml/com.example.parserxml.MainActivity}: android.os.NetworkOnMainThreadException
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.ActivityThread.access$600(ActivityThread.java:153)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1269)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.os.Looper.loop(Looper.java:137)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.ActivityThread.main(ActivityThread.java:5287)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at java.lang.reflect.Method.invokeNative(Native Method)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at java.lang.reflect.Method.invoke(Method.java:525)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at dalvik.system.NativeStart.main(Native Method)
09-12 17:09:06.065: E/AndroidRuntime(11394): Caused by: android.os.NetworkOnMainThreadException
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at com.example.parserxml.MainActivity.getInputStream(MainActivity.java:95)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at com.example.parserxml.MainActivity.onCreate(MainActivity.java:44)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.Activity.performCreate(Activity.java:5201)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-12 17:09:06.065: E/AndroidRuntime(11394):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2293)
09-12 17:09:06.065: E/AndroidRuntime(11394):    ... 11 more
4

1 回答 1

0

根据Android 文档

当应用程序尝试在其主线程上执行网络操作时引发的异常。

这仅针对面向 Honeycomb SDK 或更高版本的应用程序抛出。允许以早期 SDK 版本为目标的应用程序在其主事件循环线程上进行网络连接,但非常不鼓励这样做。请参阅文档设计响应性。

您需要在另一个线程中执行网络操作,而不是 UI 线程。

于 2013-09-12T15:25:48.333 回答