Created
July 18, 2016 07:18
-
-
Save Bahaaib/d187923e1bd2351efb7dbb10905177dd to your computer and use it in GitHub Desktop.
How to bring content from internet to your App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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