Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to show progress in a ProgressDialog while downloading

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 769
    Comment on it

    Progress dialog in android to show progress indicator/updates while downloading a file or when waiting to load a file while playing a game. Progress dialog have various features like:-

    setMessage() to display message Example: Loading... (or) Please wait....

    setTitle() method is used to set a title to the progress dialog.

    getProgress() method is used to get the current progress.

    setMax for the final length.

    setProgressStyle() to show the progress eighter horizontal progress bar or circular, spinner progress bar.

    setCancelable() to make progress dialog cancelable or not.

    dismiss() for the close.

     protected Dialog onCreateDialog(int id){
            switch (id){
                case progress_bar_type:
                    progressDialog = new ProgressDialog(this);
                    progressDialog.setMessage("Downloading file... Please wait");
                    progressDialog.setIndeterminate(false);
                    progressDialog.setMax(100);
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progressDialog.setCancelable(true);
                    progressDialog.show();
                    return progressDialog;
                default:
                    return null;
            }
        }
    

    For making the app smoother to work, we have to download the file in separate thread. Android provides a asynchronous class AsyncTask for the background processing without affecting the main thread. Before AsyncTask doInBackground() where all the work is done, we have onPreExecute() to show progress dialog and to set progress, onPostExecute() method to dismiss the dialog and showing the result after the task completed. AsyncTask has method onProgressUpdate() that you can call each time a progress is done during doInBackground().

        protected void onPreExecute(){
            super.onPreExecute();
            showDialog(progress_bar_type);
            progressDialog.show();
            progressDialog.setProgress(0);
        }
    
        @Override
        protected String doInBackground(String... params) {
    
            int count;
            try {
                InputStream input = null;
                OutputStream output = null;
                HttpURLConnection connection = null;
    
                File SDCardRoot = Environment.getExternalStorageDirectory();
                File directory = new File(SDCardRoot, "/My_folder/");
                if (!directory.exists())
                {
                    directory.mkdir();
                }
                try {
    
                    URL url = new URL(params[0]);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.connect();
    
                    String filename = "XYZ"+".pdf";
    
                    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                        return "Server returned HTTP " + connection.getResponseCode()
                                + " " + connection.getResponseMessage();
    
                    int fileLength = connection.getContentLength();
    
                    input = connection.getInputStream();
                    input = url.openStream();
                    output = new FileOutputStream(new File(directory, filename));
    
                byte data[] = new byte[1024];
    
                long total = 0;
    
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled())
                        return null;
    
                    total += count;
                    // publishing the progress....
    
            if(fileLength>0)
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / fileLength));
    
                    // writing data to file
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
                download = false;
            }
        }
    
        protected void onProgressUpdate(String... progress){
            progressDialog.setIndeterminate(false);
            progressDialog.setMax(100);
            progressDialog.setProgress(Integer.parseInt(progress[0]));
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            if (result != null)
                Toast.makeText(MainActivity.this,"Download error: "+result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(MainActivity.this,"File downloaded", Toast.LENGTH_SHORT).show();
        }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: