2

I have made a download method that works fine. It takes a String url and returns the downloaded InputStream which gets processed by XMLPullParser. Now I want to add a progressbar to the download. I have figured out that I can somehow use getContentLength() on HttpURLConnection but I do not know how to calculate the progressbar after that.

This is my code:

public static InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(15000);
    conn.setConnectTimeout(25000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setUseCaches(true);
    conn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
    conn.setRequestProperty("Accept", "application/xml");
    conn.connect();
    int size = conn.getContentLength();
    InputStream stream = conn.getInputStream();

            //calculate the progress

    return stream;      
}

Thanks!

vamosrafa
  • 685
  • 5
  • 11
  • 35
TutenStain
  • 237
  • 2
  • 6
  • 18
  • Please use the search before posting questions that have already been answered. [Here you go](http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog) – cwin Jun 15 '13 at 13:08
  • I have seen those but non of them actually returns an `InputStream` after the download which my parser needs. Or have I missed something? – TutenStain Jun 15 '13 at 13:18

1 Answers1

2

If you need to parse the content afterwards, you have (at least) two options:

  • Keep track of current position in the stream, as suggested in that Google groups answer. You have then an accurate progress as it represents both parsing and downloading progress.

  • Download the stream to a temp file (and show progress for that) and then you pass a FileInputStream to your parser (and show some more progress if required, but that should be fast compared to the download, you could consider downloading as 90% of the progress and parsing as the remaining 10% for instance).

Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124