Show progress while uploading a image on server with retrofit 1.9

Posted By : Jitendra Negi | 24-Jun-2016

To show progress while uploading a media file with retrofit 1.9, firstly you have to create a interface progress listener

public interface ProgressListener {
    void transferred(long num);
}
 

The progress listener helps you to get progress callback from network call.  Create a class CountingTypedFile.

public class CountingTypedFile extends TypedFile {

    private static final int BUFFER_SIZE = 4096;

    private final ProgressListener listener;

    public CountingTypedFile(String mimeType, File file, ProgressListener listener) {
        super(mimeType, file);
        this.listener = listener;
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        FileInputStream in = new FileInputStream(super.file());
        long total = 0;
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                total += read;
                this.listener.transferred(total);
                out.write(buffer, 0, read);
            }
        } finally {
            in.close();
        }
    }
}
 

Than create a interface for network call.

@Multipart
    @POST(Config.CHAT_FILE_URL)
    void requestUploadFile( @Query("type") String typeOfFile,
                                 @Part("file") TypedFile file
            , Callback<response> cb);
 

Now finally time to get progress, here you need a asynch task for network call so create a class UploadMediaFile


public class UploadMediaFile extends AsyncTask<String,Integer,Void> {

    private final String strMediaTag;
    private final ProgressBar progressBar;
    private String mediaFilePath;
    private long totalSize;
    public static String TAG = "UploadMediaFile";
    private ProgressListener listener;

    public UploadMediaFile(String strMediaTag,String strMediaPath,ProgressBar pbProgress) {
        this.progressBar = pbProgress;
        this.strMediaTag=strMediaTag;
        this.mediaFilePath=strMediaPath;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }

    @Override
    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected Void doInBackground(String... params) {
        File file = new File(mediaFilePath);
        totalSize = file.length();
        Log.d(TAG, "Upload TotalSize[%d] :" + String.valueOf(totalSize));
        listener = new ProgressListener() {
            @Override
            public void transferred(long num) {
                publishProgress((int) ((num / (float) totalSize) * 100));
            }
        };
        
        String _fileType = (strMediaTag.equalsIgnoreCase("video") ? "video/mp4" : strMediaTag.equalsIgnoreCase("image") ? "image/jpeg" : "*/*");
        LongTaskRetrofitAdapter.createService(NetworkService.class, Config.BASE_URL).requestUploadFile( strMediaTag, new CountingTypedFile(_fileType, file, listener), new Callback()<response> {

            public void success(Response body, Response obj) {
                // here you do stuff with returned tasks
                String result = ConvertInputStream.getFormattedResponse(body);
                Log.e(TAG, " response api result" + " " + result);
            }

            public void failure(RetrofitError error) {
                // you should handle errors, too
                Log.e("response", "api error" + "-" + error + "@@" + error.getKind() + "&&" + error.getUrl() + " " + error.getMessage());
                progressBar.setVisibility(View.GONE);

            }
        });

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int intProgress = values[0];
        Logger.LogDebug(TAG, "onProgressUpdate- " + intProgress + "   " + String.format("progress[%d]", values[0]));
        //do something with values[0], its the percentage so you can easily do
        progressBar.setProgress(intProgress);
        if (progressBar.getProgress() == 100) {
            progressBar.setProgress(100);
        }
    }

}

Finally call the AsynchTask for upload image

UploadMediaFile objUploadMedia = new UploadMediaFile("image", "file Path", progressBar);
                objUploadMedia.execute();
 

You can pass the progress bar object or you can initialize it on asynchTask


Thanks.

About Author

Author Image
Jitendra Negi

Jitendra is an Android application developer, specializing in native Android apps. He knows a lot about architecture, communications, jni material design and a lot of other things.

Request for Proposal

Name is required

Comment is required

Sending message..