Java Thread没有启动,有什么问题,我该如何解决?

时间:2013-06-27 08:23:32

标签: java android multithreading http

我是线程新手,而不是Java中最先进的,但从我的理解,以下应该正确运行,但它没有。我已经尝试过调整内容并阅读线程但无济于事。我试着搜索,但我没有得到任何明确的答案。

代码:

public void getValue(final EditText input1) // 0 all three // 1 ask // 2 buy
{
    final Handler handler = new Handler();
    final Thread thread = new Thread() {
        public void run() {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpGet httpGet = new HttpGet("http://finance.yahoo.com/d/quotes.csv?s="+input1.getText().toString()+"&f=abl1");
                HttpResponse response = null;
                try {
                    response = httpClient.execute(httpGet, localContext);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final HttpResponse finalResponse = response;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            textViews[2].setText("Last:Err2");
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(
                                            finalResponse.getEntity().getContent()
                                    ));
                            updateText( reader.readLine()); // pass data out
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (final Exception e) {
                e.printStackTrace();
        }
    }

};
    thread.start();
}

1 个答案:

答案 0 :(得分:3)

  1. 您是否致电getValue?
  2. 为什么你说它不运行呢?它看起来应该是。
  3. 在Android中,这应该由AsyncTask完成。 AsyncTask是一个将自动为您启动线程的类,然后在任务完成时在UI线程上运行第二段代码。这摆脱了笨拙的Handler构造。