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
//www.husseinnasser.com 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
 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;
                }
                      bufferReader.close();
                 
                      output = stringText;
                    
               } catch (Exception e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                 
                output= e.toString();
               }
              
                }
            };
             
           t.start();
      try {
   t.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 
 
 
 
}



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 
     fu.Run("http://geshout.com/version.txt"); 
     
     //You are clear, your activity is now active and get your string and do Whatever you want 
     String o = fu.getOutput();
     
     //Cheers!
     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.

1 comment:

  1. Thank you for explaining all the code in practical form code is very helpful when do the implements.

    ReplyDelete

Share your thoughts

Note: Only a member of this blog may post a comment.