2013-05-02 108 views
0

我有这种形式的一个按钮时提交我检索雅虎财经API库存信息,并用它来显示到3个textviewsretriving股票报价与雅虎财经

我使用url 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 =新的网址...,(即使是通过浏览器完成的裸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)

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

+0

你在UI线程上做IO的东西吗?你的代码不完整。这是第一个猜测。 – 2013-05-02 13:19:45

+0

重复:http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – laalto 2013-05-02 13:26:38

+0

@大卫即时只是显示在3 textviews,这是嵌入在一个单一的活动,我是一个全新的android,队友UI线程?它来自火星:( – 2013-05-02 13:27:45

回答

1

这是你的logcat中的关键错误消息 - > android.os.NetworkOnMainThreadException。您应该将网络访问权移动到后台线程。您可以使用IntentService,AsynchTask,Handler等来完成此操作。

查看http://developer.android.com/training/articles/perf-anr.html了解更多关于在独立线程上执行网络操作的重要性的更多信息。

相关问题