user2527166
user2527166

Reputation: 23

Java Thread not starting, what is wrong and how can I fix it?

I'm new to threading and not the most advanced in Java, but from what I understand the following should run correctly, but it doesnt. I've tried tweaking things and reading up on threads but no avail. I tried searching, but I haven't got any clear answers.

Code:

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();
}

Upvotes: 2

Views: 115

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93728

  1. Did you call getValue?
  2. Why do you say it isn't running if so? It looks like it ought to.
  3. In Android this should really be done by an AsyncTask. An AsyncTask is a class that will automatically start a thread for you, then will run a second piece of code on the UI thread when the task is done. This gets rid of the awkward Handler construct.

Upvotes: 3

Related Questions