0

我在提交时有一个带有按钮的表单我从 yahoo Finance api 检索股票信息,并使用它显示到三个文本视图上

我使用的网址 http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2

我的按钮事件处理程序是

          URL url;

            try {
                url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2");


                InputStream stream = url.openStream();
                BufferedInputStream bis = new BufferedInputStream(stream);
                ByteArrayBuffer bab = new ByteArrayBuffer(50);

                int current = 0;
                   while((current = bis.read()) != -1){
                    bab.append((byte) current);
                   }
                String stockTxt = new String(bab.toByteArray());
                String[] tokens = stockTxt.split(",");

                String stockSymbol = tokens[0];
                String stockPrice = tokens[1];
                String stockChange = tokens[2];

                String fstockSymbol = stockSymbol.substring(1, stockSymbol.length() -1);
                String fstockChange = stockChange.substring(1, stockChange.length()-3);

                symbolOut.setText(fstockSymbol);
                priceOut.setText(stockPrice);
                changeOut.setText(fstockChange);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

所以我注意到直到第一行似乎没有问题,即 url = new URL ...,(即使是通过浏览器完成的裸 http 请求,也会返回我需要的信息)

我的清单条目看起来像

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

下面是logcat的输出

05-02 18:36:32.804: D/AndroidRuntime(902): Shutting down VM 05-02 18:36:32.804: W/dalvikvm(902): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 05-02 18:36:33.113: E/AndroidRuntime(902): FATAL EXCEPTION: main 05-02 18:36:33.113: E/AndroidRuntime(902): android.os.NetworkOnMainThreadException 05-02 18:36:33.113: E/AndroidRuntime(902): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.lookupHostByName(InetAddress.java:391) 05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242) 05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByName(InetAddress.java:220) 05-02 18:36:33.113: E/AndroidRuntime(902): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)

所以任何人都知道我哪里出错了

4

1 回答 1

1

This is the key error in your LogCat message --> android.os.NetworkOnMainThreadException. You should move your network access to a background thread. You can use either an IntentService, AsynchTask, Handler, etc. to accomplish this.

Check out http://developer.android.com/training/articles/perf-anr.html for more information about why it is important to do network ops on a separate thread.

于 2013-05-02T13:25:14.127 回答