检索与雅虎财务的股票报价

时间:2013-05-02 13:17:36

标签: java android yahoo-finance

我有一个提交按钮的表格我从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)

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

1 个答案:

答案 0 :(得分:1)

这是您的LogCat消息中的关键错误 - &gt; android.os.NetworkOnMainThreadException。您应该将您的网络访问权限移动到后台线程。您可以使用IntentService,AsynchTask,Handler等来完成此任务。

查看http://developer.android.com/training/articles/perf-anr.html以获取有关在单独的线程上执行网络操作的重要性的详细信息。