Skip to content

Instantly share code, notes, and snippets.

@Bahaaib
Created July 18, 2016 07:18
Show Gist options
  • Select an option

  • Save Bahaaib/d187923e1bd2351efb7dbb10905177dd to your computer and use it in GitHub Desktop.

Select an option

Save Bahaaib/d187923e1bd2351efb7dbb10905177dd to your computer and use it in GitHub Desktop.
How to bring content from internet to your App
public class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls){
String result = ""; // send Link to Method
URL url; // initialize URL variable
HttpURLConnection urlConnection = null; // initialize HttpURLConnection which later will be responsible for establishing Conn.
try{
url = new URL(urls[0]); //calling (urls member) number 0 from the (String...)
urlConnection = (HttpURLConnection).openConnection(); // initialize the connection to the URL
InputStream in = urlConnection.getInputStream(); // connecting the HTML page to the input stream
InputStreamReader reader = new InputStreamReader(in); //Trying to read data from the input stream
int data = reader.read(); //Directing the read data to the variable (data)
while(data != -1){
char current = (char) data; //re-converting the integer stored into (data) into character by casting it
result+ = current; // add the the current char to the total result string
data = reader.read(); //continue reading till data = -1 then out the result as the HTML ends
}
return result;
}
catch (Exception e){
e.printStackTrace();
}
catch (ExecutionException e){
e.printStackTrace();
}
}
}
///@onCreate Method
DownloadTask task = new DownloadTask();
String result = null;
// Try/catch must be surrounded with, to handle any possible error
try {
result = task.excute("http://XYZ.com").get();
}
catch (InterruptedException e){
e.printStackTrace();
}
catch(ExcutionException e){
e.printStackTrace();
}
//instert the following permission line below the package name line
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment