Question

I have this Thread on a Fragment

          Thread trd = new Thread(new Runnable(){
          @Override
          public void run(){
            HttpClient hc = new DefaultHttpClient();
            HttpGet post = new HttpGet("http://www.no798.eu/notizie.php");
            HttpResponse rp = null;
            try {
                rp = hc.execute(post);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (rp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                // Server is unavailable
            }
            try {

                String str=EntityUtils.toString(rp.getEntity());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    trd.start();

How i can get out of Thread the EntityUtils String? If a try java whant a Final one-element array String...

Was it helpful?

Solution

Create a Handler in your Activity or Fragment, and pass the result of the HTTP call to it.

In your Activity/Fragment:

private final static int HANDLER_FROM_HTTP = 1;
private final Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
        final int what = msg.what;
        switch(what) {
            case HANDLER_FROM_HTTP:  {
                Bundle b = msg.getDate();
                if (b != null) {
                    String s = b.getString("result");
                    doSomething(s);
                }
            }
        }
    }
};

Then, in the run() method of your Thread above:

String str=EntityUtils.toString(rp.getEntity());
Message msg = pThreadHandler.obtainMessage(HANDLER_FROM_HTTP);
Bundle b = new Bundle();
b.putString("result", str);
msg.setData(b);
msg.sendToTarget();

This will allow you to execute doSomething() on the main UI thread to update a View, or perform some other action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top