0

I wrote a code in the Android project that uploads a file with a specific name and address to the server. But ProgressBar does not work well and does not show progress and file upload percentage. But the file upload works well and is located on the server. Now I want to show the percentage of progress in the Progress bar when uploading the file to the server to determine how much of the file has been uploaded to the server. I tried to do this with AsyncTask. My code ...

private class UploadTask extends AsyncTask<String, Integer, String> {

        private final Context context;

        public UploadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            wl.acquire(10 * 60 * 1000L /*10 minutes*/);

            try {

                String fileName = uploadFilePath + uploadFileName;

                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                File sourceFile = new File(uploadFilePath + uploadFileName);

                if (!sourceFile.isFile()) {

                    dialog.dismiss();

                    Log.e("uploadFile", "Source File not exist :"
                            + uploadFilePath + "" + uploadFileName);

                    getActivity().runOnUiThread(new Runnable() {
                        @SuppressLint("SetTextI18n")
                        public void run() {
                            messageText.setText("Source File not exist :"
                                    + uploadFilePath + "" + uploadFileName);
                        }
                    });
                    Sneaker.with(getActivity())
                            .setTitle("Error !")
                            .setMessage("Source File not exist")
                            .sneakError();

                } else {
                    try {

                        // open a URL connection to the Servlet
                        FileInputStream fileInputStream = new FileInputStream(sourceFile);
//                        URL url = new URL(upLoadServerUri);
                        URL url = new URL(sUrl[0]);

                        // Open a HTTP  connection to  the URL
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setDoInput(true); // Allow Inputs
                        conn.setDoOutput(true); // Allow Outputs
                        conn.setUseCaches(false); // Don't use a Cached Copy
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                        conn.setRequestProperty("uploaded_file", fileName);

                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        String name = key_login_userid + ".JM";
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + name + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                        // create a buffer of  maximum size
                        bytesAvailable = fileInputStream.available();

                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // read file and write it into form...
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        long total = 0;
                        while (bytesRead > 0) {
                            total++;
                            dos.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                            publishProgress((int) (bufferSize * 100 / maxBufferSize));
                        }

                        // send multipart form data necesssary after file data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                        // Responses from the server (code and message)
                        serverResponseCode = conn.getResponseCode();
                        String serverResponseMessage = conn.getResponseMessage();

                        Log.i("uploadFile", "HTTP Response is : "
                                + serverResponseMessage + ": " + serverResponseCode);

                        if (serverResponseCode == 200) {

                            getActivity().runOnUiThread(new Runnable() {
                                public void run() {

                                    messageText.setText("");

                                }
                            });
                        }

                        //close the streams //
                        fileInputStream.close();
                        dos.flush();
                        dos.close();

                    } catch (MalformedURLException ex) {

                        dialog.dismiss();
                        ex.printStackTrace();

                        getActivity().runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            public void run() {
                                messageText.setText("MalformedURLException Exception : check script url.");
                                Sneaker.with(getActivity())
                                        .setTitle("Error !")
                                        .setMessage("MalformedURLException")
                                        .sneakError();
                            }
                        });

                        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                    } catch (Exception e) {

                        dialog.dismiss();
                        e.printStackTrace();

                        getActivity().runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            public void run() {
                                messageText.setText("Got Exception : see logcat ");
                                Sneaker.with(getActivity())
                                        .setTitle("Error !")
                                        .setMessage("Got Exception : see logcat")
                                        .sneakError();

                            }
                        });
                        Log.e("Upload file to server Exception", "Exception : "
                                + e.getMessage(), e);
                    }
                    dialog.dismiss();

                } // End else block
            } finally {
                wl.release();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            dialog.setIndeterminate(false);
            dialog.setMax(100);
            dialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            if (result != null) {
                Sneaker.with(getActivity())
                        .setTitle("خطا !")
                        .setMessage("خطا در ارسال اطلاعات.")
                        .sneakError();
            } else {
                Sneaker.with(getActivity())
                        .setTitle("توجه!")
                        .setMessage("ارسال اطلاعات کامل شد.")
                        .sneakSuccess();
            }
        }

    }
  • AsyncTask is [Deprecated](https://stackoverflow.com/questions/58767733/the-asynctask-api-is-deprecated-in-android-11-what-are-the-alternatives) and not recommended at all . Use Some Other alternative for threading . – ADM Jan 20 '22 at 04:54

1 Answers1

0

You can use this code to show progress bar when using Asynctask

https://www.concretepage.com/android/android-asynctask-example-with-progress-bar

Jay_Panchal
  • 327
  • 2
  • 11