我正在制作一个 android 应用程序来跟踪股票详细信息,我将通过 csv(雅虎财经)检索数据。据我所知,在 android 4.0 中,无法在主线程上进行网络连接。因此,我将使用 asynctask 来建立连接。但是,我在参数方面遇到了一些问题。请问输入流类型可以作为参数使用吗?
public class StockDetails extends Activity {
private InputStream is = null;
private BufferedReader reader = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stock_details);
Intent i = getIntent();
String stockNo = i.getStringExtra(MainActivity.STOCK_NO).toString();
Log.i("Stock No", stockNo);
String strURL = "http://download.finance.yahoo.com/d/quotes.csv?s="+ stockNo +".HK&f=nsl1opc1";
Log.i("URL", strURL);
class HostConnection extends AsyncTask<String, Void, InputStream> {
private Exception ex;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected InputStream doInBackground(String... urls) {
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
HttpContext localContext = new BasicHttpContext();
HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} catch (Exception e) {
this.ex = e;
return null;
}
}
@Override
protected void onPostExecute(InputStream is) {
super.onPostExecute(is);
reader = new BufferedReader(new InputStreamReader(is));
}
}
new HostConnection().execute(strURL);
try {
String line;
while ((line = reader.readLine()) != null){
String[] RowData = line.split(",");
String name = RowData[0];
String symbol = RowData[1];
String currPrice = RowData[2];
String open = RowData[3];
String prevClose = RowData[4];
String change = RowData[5];
TextView stockName = (TextView)findViewById(R.id.stockName);
stockName.setText(name);
TextView stockSymbol = (TextView)findViewById(R.id.stockSym);
stockSymbol.setText(symbol);
TextView stockCurrPrice = (TextView)findViewById(R.id.currPrice);
stockCurrPrice.setText(currPrice);
TextView stockOpen = (TextView)findViewById(R.id.open);
stockOpen.setText(open);
TextView stockPrevClose = (TextView)findViewById(R.id.prevClose);
stockPrevClose.setText(prevClose);
TextView stockChange = (TextView)findViewById(R.id.change);
stockChange.setText(change);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
...
}
}
以上是我的代码,它无法执行语句return httpEntity.getContent();
并跳转到异常部分。请帮忙。谢谢!