Display url source code or online text file in android TextView

To display an online text file or source code of any web url, in a TextView, we have to do following:

  • Create a URL object from the String representation.
  • Use openStream() method to open a connection to this URL and and get the InputStream for reading from that connection.
  • Create a new BufferedReader, using a new InputStreamReader with the URL input stream.
  • Read the text, using readLine() method of BufferedReader.
But this cannot be done directly in an android project because android apps do not allow networking operation on its main UI thread.
Therefore we need to use AsyncTask class, which allows us to perform background operations and publish results on the UI thread.
To create such an online text file reader app in sketchware, follow the steps given below:

 


1. Create a new project in Sketchware. In VIEW area add a LinearV inside a ScrollV. In this add an EditText edittext1 (for writing URL), a Button button1, and a TextView textview1 (for displaying result).
 


2. Add a WebView loadUrl block in onCreate event. This is required to add INTERNET permissions in Sketchware project.
 


3. Create a More block called extracodes. Define this using an add source directly block by using following code in it:
}
private class BackTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {}

protected String doInBackground(String... address) {
String output = "";
try {
java.net.URL url = new java.net.URL(address[0]);
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
output += line;
}
in.close(); } catch (java.net.MalformedURLException e) {
output = e.getMessage();
} catch (java.io.IOException e) {
output = e.getMessage();
} catch (Exception e) {
output = e.toString();
}
return output;
}

protected void onProgressUpdate(Integer... values) {}

protected void onPostExecute(String s){
textview1.setText(s); }
 

This code defines a new AsyncTask with name BackTask. It is defined as a task which takes a String as input. In background, it converts it into a URL, then it reads the URL using a BufferedReader, and returns a String as output. onPostExecute it displays the resultant String in textview1.

4. In button1 onClick event use add source directly block and put following code in it:
new BackTask().execute(edittext1.getText().toString());
 
This code calls the AsyncTask on Button Click, to read the URL from edittext1 in background and display results in textview1.
5. Save and run the project. In the app, write any url in EditText field and click the button. You will see the source code of the url in the TextView.
 
 
 
http://www.sketchwarehelp.com/2018/08/display-url-source-code-or-online-text.html