title: showing download progress in progress bar using DownloadManager
body: <p>I am working on an android app in which i am using <code>DownloadManager</code> to download a file from a server.</p>
  
  <p><strong>Problem</strong></p>
  
  <p>While the file download is in progress, I want to show the download progress via <code>progress bar</code>. File is downloaded successfully but I am not able to show the download progress.</p>
  
  <p>Code I use to show progress  </p>
  
  <pre><code>private void startAppDownload() {
  
      ...
  
      // code to show download progress
      new Thread(new Runnable() {
          @Override
          public void run() {
              boolean isDownloading = true;
              int downloadStatus, totalBytesDownloaded, totalBytes;
  
              DownloadManager.Query downloadQuery = new DownloadManager.Query();
              downloadQuery.setFilterById(downloadID);
  
              Cursor cursor = downloadManager.query(downloadQuery);
              cursor.moveToFirst();
  
              while (isDownloading) {
  
                  totalBytesDownloaded = cursor.getInt(
                          cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
                  );
  
                  totalBytes = cursor.getInt(
                          cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
                  );
  
                  downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
  
                  if(downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
                      isDownloading = false;
                  }
  
                  final int downloadProgress = (int) ((double)totalBytesDownloaded / (double)totalBytes * 100f);
  
                  runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
                          downloadProgressBar.setProgress(downloadProgress);
                      }
                  });
              }
  
              cursor.close();
          }
      }).start();
  }
  </code></pre>
  
  <p>I logged the <code>totalBytesDownloaded</code> variable but it is always <code>zero</code> and the <code>totalBytes</code> variable is always <code>-1</code>.</p>
  
  <p>This causes <code>downloadProgress</code> variable to always be <code>zero</code>, hence <code>progress bar</code> shows no progress.</p>
  
  <p><strong>Question</strong></p>
  
  <p>What am I doing wrong here? Why is <code>totalBytesDownloaded</code> variable always equal to <code>zero</code> and <code>totalBytes</code> variable always <code>-1</code>?</p>