I have a Android application and I want to show a progress bar for downloaded weather data. I will show a weather forecast for around 5 places. The problem is when I want to get the Content-Length from the response header. The log always shows me -1(it means that the field is not set in the URLConnection variable).
This is the code I’m using:
private class DownloadWeatherData extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL("http://www.google.com/ig/api?weather=NY&hl=en&oe=utf-8");
URLConnection connection = url.openConnection();
int dataLenght = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Data lenght: " + dataLenght);
InputStream input = new BufferedInputStream(url.openStream());
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
Log.d("ANDRO_ASYNC", ""+(int)((count)));
}
input.close();
} catch (Exception e) {
}
return null;
}
}
What can I do? Or is there another way to show progress of the downloaded data?
Very often pages and other files are not delivered with a Content-Length header (sent as “chunks” of data). In that case normally browsers do not show a percentage, but a perpetual animation bar (“
// // // // //“).Of course you can always fake it when knowing the average response time of the site and transfer slowness of client.