Friday, April 19, 2013

Fetch URL Text from Android/Java Application

I searched a lot for a straight forward clean multithreaded code to do this simple task, read data from a URL and get the output. All I found were segments of codes that force close.

So I wrote a simple class do this task.

Create a new Class name it FetchURL and past this whole thing into it.

//Hussein Nasser 19-4-2013
 public class FetchURL {

 private String output;
 private String url;
 public FetchURL()
  output = "";
 public String getOutput()
  return output;
 public void Run(String u)
   url = u;
    Thread t =  new Thread() {
       public void run() {
         // Toast.makeText( mycontext , "running thread bitch", Toast.LENGTH_LONG).show();
                    URL textUrl;
               try {
                textUrl = new URL(url);
                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
                String StringBuffer;
                      String stringText = "";
                while ((StringBuffer = bufferReader.readLine()) != null) {
                 stringText += StringBuffer;
                      output = stringText;
               } catch (Exception e) {
                // TODO Auto-generated catch block
                output= e.toString();
      try {
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block

To use the code in your main activity

//Create an Instance of our Class
     FetchURL fu = new FetchURL();
     //run this shit (this will pause your current activity until you get the result, this should return 123 
     //You are clear, your activity is now active and get your string and do Whatever you want 
     String o = fu.getOutput();
     Toast.makeText(this, "output " +   fu.getOutput(), Toast.LENGTH_LONG).show();

This code allows you to read and execute PHP URL, almost anything that returns HTML I guess, anyway report any bugs to me. This code uses threading to execute the network capability And oh, make sure you have the internet permission on your Android Manifest.