Download a file from a web link in Sketchware

To download a file from any web url, we have to do following:
  • Define an AsyncTask which can do the download in background, i.e. in a thread different from the main UI thread. We need this because downloading large files on main thread may consume more memory and may lead the app to crash.
  • Use HttpURLConnection to openConnection() for the url and create an InputStream for downloading the url.
  • Create an OutputStream and write data from InputStream to File path in sdcard.
  • Show download progress using onProgressUpdate method of AsyncTask.
  • In onPreExecute() method of AsyncTask make ProgressBar VISIBLE.
  • In onPostExecute method of AsyncTask, make ProgressBar GONE.
To create such an app in Sketchware which can download file from link provided, follow the steps given below.

1. Create a new project in Sketchware. In VIEW area add an EditText edittext1 and a Button button1. Add a LinearH progresslinear, inside this add a circular ProgressBar progressbar1 and a LinearV containing a TextView textview2, and horizontal ProgressBar progressbar2.


2. Add a RequestNetwork component network. This is required only for adding INTERNET permissions in the Sketchware app.

3. Add four String variables path, filename, myurl and result, and two Number variables size and sumCount.


4. In onCreate event make progresslinear GONE.

5. Create a More block called extra. Here use codes and blocks as shown in image below.
i. In an add sources directly block put a } to close _extra(){ and then define an AsyncTask with name DownloadTask.

}
private class DownloadTask extends AsyncTask<String, Integer, String> {

ii. In another add source directly block, add onPreExecute method of AsyncTask.
@Override
protected void onPreExecute() {

iii. Use blocks to make progresslinear VISIBLE and set "Starting Download" as text of textview2, in onPreExecute.

iv. Close onPreExecute Method with a }.

}

v. Define doInBackground method of AsyncTask. Use HttpURLConnection to openConnection() for the url and create an InputStream for downloading the url.
In the code below 'in' is the InputStream, address[0] is the url, and filename is String variable retrieved from url, and result is the String variable which is used later in onPostExecute.
protected String doInBackground(String... address) {
try {
filename= URLUtil.guessFileName(address[0], null, null);
int resCode = -1;
java.io.InputStream in = null;
java.net.URL url = new java.net.URL(address[0]);
java.net.URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof java.net.HttpURLConnection)) {
throw new java.io.IOException("URL is not an Http URL"); }
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) urlConn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == java.net.HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
size = httpConn.getContentLength();

} else { result = "There was an error"; }

vi. Set String path to Join DIRECTORY_DOWNLOADS and / and filename.

vii. After that use block to write empty String to path. This is required for adding WRITE EXTERNAL STORAGE permissions to the Sketchware app.

viii. Use codes to create an OutputStream and write data from InputStream to a File at path in sdcard.
Here publishProgress( (int)Math.round( sumCount*100 / size)); is use to display the percentage of download completed. This is displayed using the onProgressUpdate method of AsyncTask.
java.io.File file = new java.io.File(path);

java.io.OutputStream output = new java.io.FileOutputStream(file);
try {
int bytesRead;
sumCount = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
sumCount += bytesRead;
if (size > 0) {
publishProgress((int)Math.round(sumCount*100 / size));
}
}
} finally {
output.close();
}
result = filename + " saved";
in.close();
} catch (java.net.MalformedURLException e) {
result = e.getMessage();
} catch (java.io.IOException e) {
result = e.getMessage();
} catch (Exception e) {
result = e.toString();
}
return result;

}

Upto here is the doInBackground method.

ix. Define onProgressUpdate method of AsyncTask. Here we display the data received from publishProgress(..) used in doInBackground method. Thus we display the percentage of download completed in textview2 and progressbar2.
protected void onProgressUpdate(Integer... values) {
textview2.setText(values[values.length - 1] + "% downloaded");
progressbar2.setProgress(values[values.length - 1]);

}

x. Define onPostExecute method of AsyncTask. Here we display the String result returned by doInBackground method as a Toast message.
protected void onPostExecute(String s){

showMessage(s);

xi. Use block to make progresslinear GONE and add } at end to close onPostExecute method.
}

We do not put } at end to close AsyncTask because we already placed a } in beginning of this more block.

6. In button1 onClick event set String myurl to edittext1 getText and use add source directly block to put following code in it:
new DownloadTask().execute(myurl);

This code calls the AsyncTask on Button Click, to download the URL from edittext1 in background.

7. Save and run the project. In the app, write any url in EditText field and click the button. If the link is valid it will be downloaded.

Comments

  1. Sketchwere ads are test ad.This ads are not showing other devices but why

    ReplyDelete
  2. Wie mache och es das die Datei einen amderen namem griegt??

    ReplyDelete
  3. I need Async task for time that will function like alarm

    ReplyDelete
  4. Sir i create a new app and 9apps uploading website convert to apps so he is not working uploading please help me

    ReplyDelete
  5. Cant open file please contact me

    ReplyDelete
  6. Hello you could leave the url link of the project so we can download😁✌

    ReplyDelete
  7. Hi!
    How can i use the asynctask and HttpsURLConnection post method to connect with PHP in Sketchware.

    Send variables and send images with post method get the result in Json object.

    Can you make tutorial on this stuff?

    Thanks for your help! :-)

    ReplyDelete
  8. Please help me a code to download by long press on image.. Please

    ReplyDelete
  9. Why in my Sketchware hv many ERROR ugh.. cn somebody resolve that?

    ReplyDelete
  10. does it works? there's no sample of pictures or videos to show your code works on downloading file or anything. and the section where we should put the download link doesn't shown any example for your blog readers, for beginners could effect an error results. please put some more details on it.

    ReplyDelete
  11. Downloading in this application is very limited. I cant download more often . Please make a new guide to download ANY files dude. Btw Thank you for the tutorial

    ReplyDelete
  12. Errors while trying to download

    No protocol

    ReplyDelete

Post a Comment

Popular posts from this blog

A Flash Light App in Sketchware

Create Music Player app in Sketchware

In Sketchware: How to create a calculator for any simple formula?

Simple car racing android game in Sketchware

Firebase auth in Sketchware for Login Activity