Implementing ProgressDialog in Multipart Upload Request
Asked Answered
P

3

7

I am using following method to upload an image from Android to server.

 public void uploadMultipart() {
        //getting name for the image
        String name = editText.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(filePath);


        progress = ProgressDialog.show(this, "Subiendo imagen",
                "Por favor, espere...", true);
        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name", name) //Adding text parameter to the request
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload


        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

Now I want to implement a ProgressDialog that should be dismissed when the upload finishes. I don´t know when the multi part request ends.

Thank you

Piassava answered 19/4, 2017 at 8:52 Comment(0)
S
10

Having this class:

public class SingleUploadBroadcastReceiver extends UploadServiceBroadcastReceiver {

    public interface Delegate {
        void onProgress(int progress);
        void onProgress(long uploadedBytes, long totalBytes);
        void onError(Exception exception);
        void onCompleted(int serverResponseCode, byte[] serverResponseBody);
        void onCancelled();
    }

    private String mUploadID;
    private Delegate mDelegate;

    public void setUploadID(String uploadID) {
        mUploadID = uploadID;
    }

    public void setDelegate(Delegate delegate) {
        mDelegate = delegate;
    }

    @Override
    public void onProgress(String uploadId, int progress) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onProgress(progress);
        }
    }

    @Override
    public void onProgress(String uploadId, long uploadedBytes, long totalBytes) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onProgress(uploadedBytes, totalBytes);
        }
    }

    @Override
    public void onError(String uploadId, Exception exception) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onError(exception);
        }
    }

    @Override
    public void onCompleted(String uploadId, int serverResponseCode, byte[] serverResponseBody) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onCompleted(serverResponseCode, serverResponseBody);
        }
    }

    @Override
    public void onCancelled(String uploadId) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onCancelled();
        }
    }
}

Then in your activity:

public class YourActivity extends Activity implements SingleUploadBroadcastReceiver.Delegate {

    private static final String TAG = "AndroidUploadService";

    private final SingleUploadBroadcastReceiver uploadReceiver =
        new SingleUploadBroadcastReceiver();

    @Override
    protected void onResume() {
        super.onResume();
        uploadReceiver.register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        uploadReceiver.unregister(this);
    }

    public void uploadMultipart(final Context context) {
        try {
            String uploadId = UUID.randomUUID().toString();
            uploadReceiver.setDelegate(this);
            uploadReceiver.setUploadID(uploadId);

            new MultipartUploadRequest(context, uploadId, "http://upload.server.com/path")
                .addFileToUpload("/absolute/path/to/your/file", "your-param-name")
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload();

        } catch (Exception exc) {
            Log.e(TAG, exc.getMessage(), exc);
        }
    }

    @Override
    public void onProgress(int progress) {
        //your implementation
    }

    @Override
    public void onProgress(long uploadedBytes, long totalBytes) {
        //your implementation
    }

    @Override
    public void onError(Exception exception) {
        //your implementation
    }

    @Override
    public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
        //your implementation
    }

    @Override
    public void onCancelled() {
        //your implementation
    }

}

Now you'll have appropriate callbacks fired upon successful/unsuccessful upload.

source

Sistrunk answered 19/4, 2017 at 9:3 Comment(4)
@override in SingleUploadBroadcastReceiver class showing error "Method does not override method from its superclass " ?Deception
@Sidhartha, which method are you talking about?Sistrunk
public void onProgress(String uploadId, int progress), Its all the methods which is under SingleUploadBroadcastReceiver class .Deception
@Sistrunk hey bro i used this but on oreo devices showing error while setting .setNotificationConfig(new UploadNotificationConfig()) can u please help me outMacedonian
P
4

Here is the sample method, Start the progress dialog on click and close it on onCompleted

public void uploadMultipart() {

        try {
            String path = getPath(filePath);
            final File file = new File(path);
            final String namFile = file.getName();
            final String ext = getMimeType(path);

            Toast.makeText(this, "Uploading file. Please wait...", Toast.LENGTH_SHORT).show();
            final String uploadId = UUID.randomUUID().toString();
            //Creating a multi part request

            String boundary = "---------------------------14737809831466499882746641449";
            new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                                        .addHeader("Content-Type", "multipart/form-data; boundary="+boundary)
                                        .addFileToUpload(path, "image") //Adding file
                                        .setNotificationConfig(new UploadNotificationConfig())
                                        .setMaxRetries(2)
                    .setDelegate(new UploadStatusDelegate() {
                        @Override
                        public void onProgress(Context context, UploadInfo uploadInfo) {
                            // your code here
                            Log.d("On Progress", String.valueOf(uploadInfo));
                        }

                        @Override
                        public void onError(Context context, UploadInfo uploadInfo, Exception exception) {
                            // your code here
                            Log.d("On error", String.valueOf(exception));
                        }

                        @Override
                        public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {

                            // YourClass obj = new Gson().fromJson(serverResponse.getBodyAsString(), YourClass.class);
                            Log.d("serverResponse", String.valueOf(serverResponse));

                        }

                        @Override
                        public void onCancelled(Context context, UploadInfo uploadInfo) {
                            // your code here
                            Log.d("On cancled", String.valueOf(uploadInfo));
                        }
                    })
                    .startUpload();

        } catch (Exception exc) {
           // Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, "Error While uploading...", Toast.LENGTH_SHORT).show();
        }
    }
Polemist answered 19/4, 2017 at 9:4 Comment(1)
Thank you, i have tried the answer by azizbekian and is good for me.Piassava
C
0
public void upload_file_multipart() {

    String url = " http://server.printme.uz/v1/order/make-order";

    try {
        String uploadId = UUID.randomUUID().toString();
        uploadReceiver.setDelegate((SingleUploadBroadcastReceiver.Delegate) this);
        uploadReceiver.setUploadID(uploadId);

        //Creating a multi part request
        MultipartUploadRequest request = new MultipartUploadRequest(this, uploadId, UPLOAD_URL);
        request.addFileToUpload(images.getPath(), "url");
        request.setMaxRetries(2);
        request.startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

Add this code your Activity class

@Override
public void onClick(View v) {

    if (v.getId() == R.id.btn_id) {
        upload_file_multipart();

        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMessage("Uploading photo, please wait.");
        dialog.setMax(100);
        dialog.setCancelable(true);
        dialog.show();
    }
}

implements SingleUploadBroadcastReceiver.Delegate to your Activity and declare like bellow

public class YourActivity extends AppCompatActivity implements SingleUploadBroadcastReceiver.Delegate {

private final SingleUploadBroadcastReceiver uploadReceiver =
        new SingleUploadBroadcastReceiver();
ProgressDialog dialog;

@Override
protected void onResume() {
    super.onResume();
    uploadReceiver.register(this);
}

@Override
protected void onPause() {
    super.onPause();
    uploadReceiver.unregister(this);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_images);

    //your codes
}

@Override
public void onProgress(int progress) {
    Log.d("PROGRESS", "progress = " + progress);
    dialog.setProgress(progress);
}

@Override
public void onProgress(long uploadedBytes, long totalBytes) {

}

@Override
public void onError(Exception exception) {

}

@Override
public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
    dialog.dismiss();
}

@Override
public void onCancelled() {

}

Here is SingleUploadBroadcastReceiver class

import net.gotev.uploadservice.UploadServiceBroadcastReceiver;

public class SingleUploadBroadcastReceiver extends UploadServiceBroadcastReceiver {

public interface Delegate {
    void onProgress(int progress);
    void onProgress(long uploadedBytes, long totalBytes);
    void onError(Exception exception);
    void onCompleted(int serverResponseCode, byte[] serverResponseBody);
    void onCancelled();
}

private String mUploadID;
private Delegate mDelegate;

public void setUploadID(String uploadID) {
    mUploadID = uploadID;
}

public void setDelegate(Delegate delegate) {
    mDelegate = delegate;
}

@Override
public void onProgress(String uploadId, int progress) {
    if (uploadId.equals(mUploadID) && mDelegate != null) {
        mDelegate.onProgress(progress);
    }
}

@Override
public void onProgress(String uploadId, long uploadedBytes, long totalBytes) {
    if (uploadId.equals(mUploadID) && mDelegate != null) {
        mDelegate.onProgress(uploadedBytes, totalBytes);
    }
}

@Override
public void onError(String uploadId, Exception exception) {
    if (uploadId.equals(mUploadID) && mDelegate != null) {
        mDelegate.onError(exception);
    }
}

@Override
public void onCompleted(String uploadId, int serverResponseCode, byte[] serverResponseBody) {
    if (uploadId.equals(mUploadID) && mDelegate != null) {
        mDelegate.onCompleted(serverResponseCode, serverResponseBody);
    }
}

@Override
public void onCancelled(String uploadId) {
    if (uploadId.equals(mUploadID) && mDelegate != null) {
        mDelegate.onCancelled();
    }
}
}
Curvet answered 15/6, 2017 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.