- 重點程式碼
<uses-permission android:name="android.permission.INTERNET"/>2. GAD01.java
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.util.Stack;
public class GAD01 extends Activity {
Handler handler = new Handler();
Stack<String> sStockIds = new Stack<String>();
Stack<String> sStockQuotes = new Stack<String>();
Button bSearch = null;
EditText etStockId = null;
EditText etStockQuotes = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bSearch = (Button) this.findViewById(R.id.bSearch);
etStockId = (EditText) this.findViewById(R.id.etStockId);
etStockQuotes = (EditText) this.findViewById(R.id.etStockQuotes);
// TODO: implement the click event of bSearch
bSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
sStockIds.clear();
sStockQuotes.clear();
etStockQuotes.setText("");
String stockId = etStockId.getText().toString();
for (String id : stockId.split(" ")) {
sStockIds.push(id);
new Thread(doQueryStockQuotes).start();
}
}
});
}
private Runnable doQueryStockQuotes = new Runnable() {
public void run() {
while (!sStockIds.empty()) {
String StockId = sStockIds.pop();
String StockUrl = "http://download.finance.yahoo.com/d/quotes.csv?s="
+ StockId + "&f=a";
HttpGet httpget = new HttpGet(StockUrl);
try {
HttpResponse response = new DefaultHttpClient()
.execute(httpget);
String stockQuotes = EntityUtils.toString(response
.getEntity());
sStockQuotes.push(StockId + " : " + stockQuotes);
handler.post(doUpdateGUI);
} catch (Exception e) {
}
}
}
};
private Runnable doUpdateGUI = new Runnable() {
public void run() {
while (!sStockQuotes.empty()) {
String stockQuotes = sStockQuotes.pop();
etStockQuotes.setText(etStockQuotes.getText().toString()
+ stockQuotes);
}
}
};
}
沒有留言:
張貼留言