[英]Why is my calculated percentage turning negative in Android SDK?
I am hoping that this is going to be a silly thing that I am missing, but I have been banging my head against the keyboard trying to figure out where I am going wrong. 我希望这将是一件我想念的愚蠢的事情,但是我一直在用键盘敲打我的头,以弄清楚我要去哪里错了。
I am trying to update a ProgressBar from a DownloadManager in a new Thread. 我正在尝试在新线程中从DownloadManager更新ProgressBar。 This is working correctly until around halfway, where the ProgressBar resets back to the beginning.
这可以正常工作,直到大约一半,ProgressBar重设回开始。 From putting in some debug code, I have isolated the issue to this line:
通过放入一些调试代码,我将问题隔离到了这一行:
final int dl_progress = (bytes_downloaded*100)/bytes_total;
dl_progress
is turning negative halfway through the file downloading! dl_progress
在文件下载中途dl_progress
负值! Relevant code block and log output below: 相关代码块和日志输出如下:
@Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
getActivity().runOnUiThread(new Runnable() {
public void run() {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
final int dl_progress = (bytes_downloaded*100)/bytes_total;
Log.d("Download", bytes_downloaded + " of " + bytes_total + " (" + dl_progress + "%)");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
cursor.close();
}
}
And here's the debug: 这是调试:
D/Download(18228): 7614 of 38577287 (0%)
D/Download(18228): 4226950 of 38577287 (10%)
D/Download(18228): 8578734 of 38577287 (22%)
D/Download(18228): 13207130 of 38577287 (34%)
D/Download(18228): 16539590 of 38577287 (42%)
D/Download(18228): 22287422 of 38577287 (-53%)
D/Download(18228): 28363958 of 38577287 (-37%)
D/Download(18228): 32550806 of 38577287 (-26%)
D/Download(18228): 38577287 of 38577287 (-11%)
I'm certain it's me doing something silly, but I cannot see the wood for the trees in this case, can anybody shed any light? 我确定这是我在做些愚蠢的事情,但是在这种情况下我看不到树木的木头,有人能照亮吗?
Thank you kindly. 非常感谢你。
当您将它们乘以100时,它们的值超过了整数的最大值。
The intermediate result of bytes_downloaded*100
overflows the supported range of an int (> 2^31-1) and gives you a negative result. bytes_downloaded*100
的中间结果溢出了int(> 2 ^ 31-1)的支持范围,并给您负面的结果。
You can solve it by using a long and cast the final result back to an int: 您可以通过使用long将其最终结果转换回int来解决:
final int dl_progress = (int)((bytes_downloaded*100L)/bytes_total);
将dl_progress
从int
更改为long
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.