Sunday, December 5, 2010

Non UI blocking network call / web request

Code snippet to fetche content(s) from the web without blocking the UI (runs in the background in a Thread). Once finished, it posts a Handler that is picked up by the UI as soon as possible.
It is widely used in most of commercial/production level apps

Code Snippet:-
import org.apache.http.util.ByteArrayBuffer;

public class Iconic extends Activity {
    private String html = "";
    private Handler mHandler;

    public void onCreate(Bundle savedInstanceState) {
        mHandler = new Handler();

    private Thread checkUpdate = new Thread() {
        public void run() {
            try {
                URL updateURL = new URL("");
                URLConnection conn = updateURL.openConnection();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;
                while((current = != -1){

                /* Convert the Bytes read to a String. */
                html = new String(baf.toByteArray());
            } catch (Exception e) {

    private Runnable showUpdate = new Runnable(){
           public void run(){
            Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show();

1 comment:

Jazzie Casas said...

Java may be the main choice for enterprise development now, but it’s days are numbered as the only stalwart option to go with.

Let’s face it, many of these so called “enterprise applications” could easily have been written much faster and with less overhead using technologies like Python, PHP, et al.

uml training