Updating the progress dialog on an uploading process

故事扮演 提交于 2019-12-04 19:06:10

problems i noticed are :

  • your bufferSize can be total file length. so, in one read itself, the buffer can be full. i changed it to 512 to get noticeable change in progressbar
  • your resets progress variable inside the loop
  • also, you are writing the entire buffer (ie from 0 to bufferSize) to the output stream. not the actual `bytesRead. at the last portions you may get error values.
  • before reading again, you are not restting the buffer

updated code

bufferSize = 512;
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
progress=0;

while (bytesRead > 0)
{   

    progress+=bytesRead;
    outputStream.write(buffer, 0, bytesRead);
    bytesAvailable = fileInputStream.available(); 
    publishProgress((int)((progress*100)/(file.length())));
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}//end of while statement
fileInputStream.close();
publishProgress(100); 
outputStream.flush();
outputStream.close();

Your loop should look something like this, there was a couple of logical errors in your code.

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
progress=0;
progress+=bytesRead;

while (bytesRead > 0)
{   
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available(); 
    publishProgress((int)((progress/file.length())*100));
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    progress+=bytesRead;
}//end of while statement

Update: I just noticed, that you use a buffer with 20MB, change maxBufferSize to int maxBufferSize = 1024, and it should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!