java - Why is my calculated percentage turning negative in Android SDK? -


i hoping going silly thing missing, have been banging head against keyboard trying figure out going wrong.

i trying update progressbar downloadmanager in new thread. working correctly until around halfway, progressbar resets beginning. putting in debug code, have isolated issue line:

final int dl_progress = (bytes_downloaded*100)/bytes_total; 

dl_progress turning negative halfway through file downloading! relevant code block , 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 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 it's me doing silly, cannot see wood trees in case, can shed light?

thank kindly.

the intermediate result of bytes_downloaded*100 overflows supported range of int (> 2^31-1) , gives negative result.

you can solve using long , cast final result int:

final int dl_progress = (int)((bytes_downloaded*100l)/bytes_total);


Comments