Non-Blocking Web-Request

7 votes · 11 comments

This code fetches content 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.

raw ·
copy
· download
import java.io.BufferedInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.apache.http.util.ByteArrayBuffer; public class Iconic extends Activity { private String html = ""; private Handler mHandler; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); checkUpdate.start(); } private Thread checkUpdate = new Thread() { public void run() { try { URL updateURL = new URL("http://iconic.4feets.com/update"); URLConnection conn = updateURL.openConnection(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /* Convert the Bytes read to a String. */ html = new String(baf.toByteArray()); mHandler.post(showUpdate); } catch (Exception e) { } } }; private Runnable showUpdate = new Runnable(){ public void run(){ Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show(); } }; }
Add a comment

11 Comments

Nice. I just bookmarked this site. Not sure why it's so hard to find logical code like this on the web but alas, it is. Thanks for posting!

Reply · May 2, 2009, 6:32 a.m.

Adding the import lines would be helpful. I get an unknown socket error when I import java.net. I can't find URL and URLConnection in android.net.

Reply · May 5, 2009, 10:42 p.m.

Re: Derek. I've added the import lines now. Hope that helps!

Reply · May 5, 2009, 11:29 p.m.

I didn't realize I'd have to set the Allow Internet permission to the Manifest for the emulator.

[brackets removed] uses-permission android:name="android.permission.INTERNET"

Reply · May 6, 2009, 1:37 a.m.

hi...i just gone through the code...it is very helpful..can u pls able to add progress dialog or waiting dialog which i am looking through net ... thanks

Reply · May 13, 2009, 2:02 p.m.

hi sheik - you might want to try android.os.AsyncTask and use the method onProgressUpdate().

Reply · May 26, 2009, 12:09 p.m.

I agree with billy, you should use AsyncTask that's already in the api ... Google have already written this code for you... you just need to know its there and use it.

Reply · June 21, 2009, 5:57 p.m.

i'm wondering.. why not just write "Toast.maketext..." instead of "mHandler.post(showUpdate)" ?...

Reply · March 30, 2011, 2:20 p.m.

Because it's started from within a Thread, which doesn't allow you to use the UI (and Toast won't work in that case). With the handler we bring it into the UI thread where Toast works.

Reply · March 30, 2011, 2:59 p.m.

Another alternative to using the mHandler approach is to put Toast in an AsyncTask and call from the main UI thread like this:

    private class ToastMessageTask extends AsyncTask<String, String, String> {
    String toastMessage;

    @Override
    protected String doInBackground(String... params) {
        toastMessage = params[0];
        return toastMessage;
    }

    protected void OnProgressUpdate(String... values) { 
        super.onProgressUpdate(values);
    }

    protected void onPostExecute(String result){
           Toast toast = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
           toast.show();
    }
}

// to use:
    new ToastMessageTask().execute("This is a TOAST message!");
Reply · Sept. 7, 2011, 11:30 a.m.

Node.js ;)

Reply · Sept. 28, 2011, 3:48 p.m.