0

I did read similar questions ,but nothing works for me . The problem is method getProgress() returns very big value (such as 16300 ).What did i do wrong?

see my code

 public void download()
{
    RandomAccessFile file = null;
    InputStream inputStream = null;
    HttpURLConnection connection = null;
    try
    {
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();
        String connectLength = connection.getHeaderField("Content-Length");

        if(connectLength == null || Integer.parseInt(connectLength) < 1 || connectLength.equals(""))
            error();

        size = Long.parseLong(connectLength);
        file = new RandomAccessFile(filePath,"rw");
        inputStream = new BufferedInputStream(url.openStream());
        int read ;

        while((read = inputStream.read(buffer)) > 0 && status == States.DOWNLOADING)
        {
            file.write(buffer,0,read);
            downloadedS += read;
        }
    }
}
 public float getProgress()
    { 
        return ((float)downloadedS/size)*100;
    }
dooplaye
  • 999
  • 13
  • 28
  • does "Content-Length" has the correct size of the response ? – Eugen Halca Oct 08 '13 at 15:27
  • What's the type of `downloadedS`? Where do you init and/or reset it? – blgt Oct 08 '13 at 15:29
  • downloadedS is long; init in constructor . (public Download(){ downloadedS = 0;size = 0;} – dooplaye Oct 08 '13 at 15:33
  • @EugenHalca i tried connection.getContentLenght() but it also doesn't work correctly; – dooplaye Oct 08 '13 at 15:36
  • @dooplaye try [this](http://stackoverflow.com/a/5463984/1029621) to calculate the response size – Eugen Halca Oct 08 '13 at 15:39
  • I don't think your usage of `connection.getHeaderField("Content-Length")` returns what you think it returns. Someone with better knowledge of http headers should be able to give a full answer though. On a side note, it's good practice to zero out `downloadedS` before the loop where you increment it. – blgt Oct 08 '13 at 16:02
  • @blgt connection.getHeaderField("Content-Length") always return 172 ; how can i get real size of file? – dooplaye Oct 08 '13 at 16:05

1 Answers1

1

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask

resource8218
  • 1,445
  • 1
  • 20
  • 33