{"id":1498,"date":"2022-10-14T12:54:36","date_gmt":"2022-10-14T12:54:36","guid":{"rendered":"https:\/\/infotheme.net\/blog\/?p=1498"},"modified":"2022-10-14T14:17:01","modified_gmt":"2022-10-14T14:17:01","slug":"android-downloading-file-by-showing-progress-bar","status":"publish","type":"post","link":"https:\/\/infotheme.net\/blog\/android-downloading-file-by-showing-progress-bar\/","title":{"rendered":"Android Downloading File by Showing Progress Bar"},"content":{"rendered":"\n<p>When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user.<br>This is a good User Experience practice. In this tutorial i will be discussing the implementation of a process-progress dialog.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><a href=\"https:\/\/infotheme.net\/blog\/wp-content\/uploads\/2022\/10\/Green-Modern-Geometric-Flash-Sale-Facebook-Ad-2-1.png\"><img loading=\"lazy\" width=\"1024\" height=\"536\" src=\"https:\/\/infotheme.net\/blog\/wp-content\/uploads\/2022\/10\/Green-Modern-Geometric-Flash-Sale-Facebook-Ad-2-1-1024x536.png\" alt=\"Android Downloading File by Showing Progress Bar\" class=\"wp-image-1500\" srcset=\"https:\/\/infotheme.net\/blog\/wp-content\/uploads\/2022\/10\/Green-Modern-Geometric-Flash-Sale-Facebook-Ad-2-1-1024x536.png 1024w, https:\/\/infotheme.net\/blog\/wp-content\/uploads\/2022\/10\/Green-Modern-Geometric-Flash-Sale-Facebook-Ad-2-1-300x157.png 300w, https:\/\/infotheme.net\/blog\/wp-content\/uploads\/2022\/10\/Green-Modern-Geometric-Flash-Sale-Facebook-Ad-2-1-768x402.png 768w, https:\/\/infotheme.net\/blog\/wp-content\/uploads\/2022\/10\/Green-Modern-Geometric-Flash-Sale-Facebook-Ad-2-1.png 1200w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n\n\n\n<p>As an example, i am displaying a progress bar that runs while the app downloads an image from the web. And once the image is downloaded<br>completely i am showing the image in a image view. You could modify this example and try it with any file type you may wish. That could be fun!<\/p>\n\n\n\n<h3>Creating new Project<\/h3>\n\n\n\n<p><strong>1<\/strong>. Create a new project and fill all the details.&nbsp;<strong>File \u21d2 New \u21d2 Android Project<\/strong><br><strong>2<\/strong>. Open your main.xml are create a button to show download progress bar. Also define a ImageView to show downloaded image. Paste the following code in your&nbsp;<strong>main.xml<\/strong><\/p>\n\n\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmain.xml\n&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;LinearLayout xmlns:android=&quot;http:\/\/schemas.android.com\/apk\/res\/android&quot;\n    android:layout_width=&quot;fill_parent&quot;\n    android:layout_height=&quot;fill_parent&quot;\n    android:orientation=&quot;vertical&quot; &gt;\n \n    &lt;!-- Download Button --&gt;\n    &lt;Button android:id=&quot;@+id\/btnProgressBar&quot;\n        android:layout_width=&quot;match_parent&quot;\n        android:layout_height=&quot;wrap_content&quot;\n        android:text=&quot;Download File with Progress Bar&quot;\n        android:layout_marginTop=&quot;50dip&quot;\/&gt;\n \n    &lt;!-- Image view to show image after downloading --&gt;\n    &lt;ImageView android:id=&quot;@+id\/my_image&quot;\n        android:layout_width=&quot;fill_parent&quot;\n        android:layout_height=&quot;wrap_content&quot;\/&gt;\n \n&lt;\/LinearLayout&gt;\n<\/pre>\n\n\n<p><strong>3<\/strong>. Now in your main activity class import necessary classes and buttons. I am starting a new asynctask to download the file after clicking on show progress bar button.<\/p>\n\n\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\npublic class AndroidDownloadFileByProgressBarActivity extends Activity {\n \n    \/\/ button to show progress dialog\n    Button btnShowProgress\n \n    \/\/ Progress Dialog\n    private ProgressDialog pDialog;\n \n    \/\/ Progress dialog type (0 - for Horizontal progress bar)\n    public static final int progress_bar_type = 0; \n \n    \/\/ File url to download\n    private static String file_url = &quot;https:\/\/api.infotheme.net\/progressdialog\/hive.jpg&quot;;\n \n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.main);\n \n        \/\/ show progress bar button\n        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);\n        \/\/ Image view to show image after downloading\n        my_image = (ImageView) findViewById(R.id.my_image);\n \n        \/**\n         * Show Progress bar click event\n         * *\/\n        btnShowProgress.setOnClickListener(new View.OnClickListener() {\n \n            @Override\n            public void onClick(View v) {\n                \/\/ starting new Async Task\n                new DownloadFileFromURL().execute(file_url);\n            }\n        });\n    }\n<\/pre>\n\n\n<p><strong>4<\/strong>. Progress Dialog can be shown using&nbsp;<a href=\"http:\/\/developer.android.com\/reference\/android\/app\/ProgressDialog.html\" data-type=\"URL\" data-id=\"http:\/\/developer.android.com\/reference\/android\/app\/ProgressDialog.html\" rel=\"nofollow noopener\" target=\"_blank\">ProgressDialog<\/a> class. It is a subclass of normal&nbsp;<a href=\"http:\/\/developer.android.com\/reference\/android\/app\/AlertDialog.html\" data-type=\"URL\" data-id=\"http:\/\/developer.android.com\/reference\/android\/app\/AlertDialog.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">AlertDialog<\/a>&nbsp;class. So add an alert method in your main activity class.<\/p>\n\n\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n\/**\n * Showing Dialog\n * *\/\n@Override\nprotected Dialog onCreateDialog(int id) {\n    switch (id) {\n    case progress_bar_type:\n        pDialog = new ProgressDialog(this);\n        pDialog.setMessage(&quot;Downloading file. Please wait...&quot;);\n        pDialog.setIndeterminate(false);\n        pDialog.setMax(100);\n        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n        pDialog.setCancelable(true);\n        pDialog.show();\n        return pDialog;\n    default:\n        return null;\n    }\n}\n<\/pre>\n\n\n<p><strong>5<\/strong>. Now we need to add our Async Background thread to download file from url. In your main activity add a&nbsp;<strong>asynctask<\/strong>&nbsp;class and name it as&nbsp;<strong>DownloadFileFromURL()<\/strong>. After downloading image from the web i am reading the downloaded image from the sdcard and displaying in a imageview.<\/p>\n\n\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n\/**\n * Background Async Task to download file\n * *\/\nclass DownloadFileFromURL extends AsyncTask&lt;String, String, String&gt; {\n \n    \/**\n     * Before starting background thread\n     * Show Progress Bar Dialog\n     * *\/\n    @Override\n    protected void onPreExecute() {\n        super.onPreExecute();\n        showDialog(progress_bar_type);\n    }\n \n    \/**\n     * Downloading file in background thread\n     * *\/\n    @Override\n    protected String doInBackground(String... f_url) {\n        int count;\n        try {\n            URL url = new URL(f_url[0]);\n            URLConnection conection = url.openConnection();\n            conection.connect();\n            \/\/ getting file length\n            int lenghtOfFile = conection.getContentLength();\n \n            \/\/ input stream to read file - with 8k buffer\n            InputStream input = new BufferedInputStream(url.openStream(), 8192);\n \n            \/\/ Output stream to write file\n            OutputStream output = new FileOutputStream(&quot;\/sdcard\/downloadedfile.jpg&quot;);\n \n            byte data[] = new byte[1024];\n \n            long total = 0;\n \n            while ((count = input.read(data)) != -1) {\n                total += count;\n                \/\/ publishing the progress....\n                \/\/ After this onProgressUpdate will be called\n                publishProgress(&quot;&quot;+(int)((total*100)\/lenghtOfFile));\n \n                \/\/ writing data to file\n                output.write(data, 0, count);\n            }\n \n            \/\/ flushing output\n            output.flush();\n \n            \/\/ closing streams\n            output.close();\n            input.close();\n \n        } catch (Exception e) {\n            Log.e(&quot;Error: &quot;, e.getMessage());\n        }\n \n        return null;\n    }\n \n    \/**\n     * Updating progress bar\n     * *\/\n    protected void onProgressUpdate(String... progress) {\n        \/\/ setting progress percentage\n        pDialog.setProgress(Integer.parseInt(progress[0]));\n   }\n \n    \/**\n     * After completing background task\n     * Dismiss the progress dialog\n     * **\/\n    @Override\n    protected void onPostExecute(String file_url) {\n        \/\/ dismiss the dialog after the file was downloaded\n        dismissDialog(progress_bar_type);\n \n        \/\/ Displaying downloaded image into image view\n        \/\/ Reading image path from sdcard\n        String imagePath = Environment.getExternalStorageDirectory().toString() + &quot;\/downloadedfile.jpg&quot;;\n        \/\/ setting downloaded into image view\n        my_image.setImageDrawable(Drawable.createFromPath(imagePath));\n    }\n \n}\n<\/pre>\n\n\n<p><strong>6<\/strong>. Open your&nbsp;<strong>AndroidManifest.xml<\/strong>&nbsp;file and add&nbsp;<strong>internet connect permission<\/strong>&nbsp;and&nbsp;<strong>writing to sdcard permission<\/strong>.<\/p>\n\n\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nAndroidManifest.xml\n&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;manifest xmlns:android=&quot;http:\/\/schemas.android.com\/apk\/res\/android&quot;\n    package=&quot;com.example.infotheme&quot;\n    android:versionCode=&quot;1&quot;\n    android:versionName=&quot;1.0&quot; &gt;\n \n    &lt;uses-sdk android:minSdkVersion=&quot;8&quot; \/&gt;\n \n    &lt;application\n        android:icon=&quot;@drawable\/ic_launcher&quot;\n        android:label=&quot;@string\/app_name&quot; &gt;\n        &lt;activity\n            android:name=&quot;.AndroidDownloadFileByProgressBarActivity&quot;\n            android:label=&quot;@string\/app_name&quot; &gt;\n            &lt;intent-filter&gt;\n                &lt;action android:name=&quot;android.intent.action.MAIN&quot; \/&gt;\n \n                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; \/&gt;\n            &lt;\/intent-filter&gt;\n        &lt;\/activity&gt;\n    &lt;\/application&gt;\n \n    &lt;!-- Permission: Allow Connect to Internet --&gt;\n    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; \/&gt;\n    &lt;!-- Permission: Writing to SDCard --&gt;\n    &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; \/&gt;\n \n&lt;\/manifest&gt;\n<\/pre>\n\n\n<p><strong>7<\/strong>. Run your Application and click on show progress bar button to see your progress bar. You can see the downloaded image in imageView once it is downloaded.<\/p>\n\n\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\npackage com.example.infotheme;\n \nimport java.io.BufferedInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.URL;\nimport java.net.URLConnection;\n \nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.graphics.drawable.Drawable;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\n \npublic class AndroidDownloadFileByProgressBarActivity extends Activity {\n \n    \/\/ button to show progress dialog\n    Button btnShowProgress;\n \n    \/\/ Progress Dialog\n    private ProgressDialog pDialog;\n    ImageView my_image;\n    \/\/ Progress dialog type (0 - for Horizontal progress bar)\n    public static final int progress_bar_type = 0; \n \n    \/\/ File url to download\n    private static String file_url = &quot;https:\/\/api.infotheme.net\/progressdialog\/hive.jpg&quot;;\n \n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.main);\n \n        \/\/ show progress bar button\n        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);\n        \/\/ Image view to show image after downloading\n        my_image = (ImageView) findViewById(R.id.my_image);\n        \/**\n         * Show Progress bar click event\n         * *\/\n        btnShowProgress.setOnClickListener(new View.OnClickListener() {\n \n            @Override\n            public void onClick(View v) {\n                \/\/ starting new Async Task\n                new DownloadFileFromURL().execute(file_url);\n            }\n        });\n    }\n \n    \/**\n     * Showing Dialog\n     * *\/\n    @Override\n    protected Dialog onCreateDialog(int id) {\n        switch (id) {\n        case progress_bar_type: \/\/ we set this to 0\n            pDialog = new ProgressDialog(this);\n            pDialog.setMessage(&quot;Downloading file. Please wait...&quot;);\n            pDialog.setIndeterminate(false);\n            pDialog.setMax(100);\n            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n            pDialog.setCancelable(true);\n            pDialog.show();\n            return pDialog;\n        default:\n            return null;\n        }\n    }\n \n    \/**\n     * Background Async Task to download file\n     * *\/\n    class DownloadFileFromURL extends AsyncTask&lt;String, String, String&gt; {\n \n        \/**\n         * Before starting background thread\n         * Show Progress Bar Dialog\n         * *\/\n        @Override\n        protected void onPreExecute() {\n            super.onPreExecute();\n            showDialog(progress_bar_type);\n        }\n \n        \/**\n         * Downloading file in background thread\n         * *\/\n        @Override\n        protected String doInBackground(String... f_url) {\n            int count;\n            try {\n                URL url = new URL(f_url[0]);\n                URLConnection conection = url.openConnection();\n                conection.connect();\n                \/\/ this will be useful so that you can show a tipical 0-100% progress bar\n                int lenghtOfFile = conection.getContentLength();\n \n                \/\/ download the file\n                InputStream input = new BufferedInputStream(url.openStream(), 8192);\n \n                \/\/ Output stream\n                OutputStream output = new FileOutputStream(&quot;\/sdcard\/downloadedfile.jpg&quot;);\n \n                byte data[] = new byte[1024];\n \n                long total = 0;\n \n                while ((count = input.read(data)) != -1) {\n                    total += count;\n                    \/\/ publishing the progress....\n                    \/\/ After this onProgressUpdate will be called\n                    publishProgress(&quot;&quot;+(int)((total*100)\/lenghtOfFile));\n \n                    \/\/ writing data to file\n                    output.write(data, 0, count);\n                }\n \n                \/\/ flushing output\n                output.flush();\n \n                \/\/ closing streams\n                output.close();\n                input.close();\n \n            } catch (Exception e) {\n                Log.e(&quot;Error: &quot;, e.getMessage());\n            }\n \n            return null;\n        }\n \n        \/**\n         * Updating progress bar\n         * *\/\n        protected void onProgressUpdate(String... progress) {\n            \/\/ setting progress percentage\n            pDialog.setProgress(Integer.parseInt(progress[0]));\n       }\n \n        \/**\n         * After completing background task\n         * Dismiss the progress dialog\n         * **\/\n        @Override\n        protected void onPostExecute(String file_url) {\n            \/\/ dismiss the dialog after the file was downloaded\n            dismissDialog(progress_bar_type);\n \n            \/\/ Displaying downloaded image into image view\n            \/\/ Reading image path from sdcard\n            String imagePath = Environment.getExternalStorageDirectory().toString() + &quot;\/downloadedfile.jpg&quot;;\n            \/\/ setting downloaded into image view\n            my_image.setImageDrawable(Drawable.createFromPath(imagePath));\n        }\n \n    }\n}\n<\/pre>\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/infotheme.net\/blog\/android-downloading-file-by-showing-progress-bar\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":1500,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[157,135,1],"tags":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/posts\/1498"}],"collection":[{"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/comments?post=1498"}],"version-history":[{"count":2,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/posts\/1498\/revisions"}],"predecessor-version":[{"id":1528,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/posts\/1498\/revisions\/1528"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/media\/1500"}],"wp:attachment":[{"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/media?parent=1498"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/categories?post=1498"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/infotheme.net\/blog\/wp-json\/wp\/v2\/tags?post=1498"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}