Description:
I have a grid view with 4 items in landscape mode and 3 items on portrait mode. The grid element is a magazine thumbnail. On click of a thumbnail downloading of the magazine starts and a horizontal progress bar appears showing progress of download. But when i click to two thumbnails one after another , the progress bar of later clicked thumbnail only updates and at last corrupted magazine gets downloaded.
I have used asynchronous task for magazine download.
Code:
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
progress = (ProgressBar) arg1.findViewById(R.id.progress);
thumbnail = (ImageView) arg1.findViewById(R.id.thumbnail);
thumbnail.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Download Magazine
downloadMagazine.execute(bank.get(index).getPdfLink());
}
});
}
class DownloadMagazineTask extends AsyncTask<String, Integer, Long> {
File sdDir = Environment.getExternalStorageDirectory();
@Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
}
@Override
protected Long doInBackground(String... arg0) {
String[] urls = arg0;
try {
URL url = new URL(urls[0]);
URLConnection con = url.openConnection();
int fileLength = con.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
File file = null;
File dir = new File(sdDir + "/BeSpoken/pdfs");
boolean flag = dir.mkdirs();
if (flag)
System.out.println("Directory created");
else {
System.out.println("Directory not created");
file = new File(dir+ "/"+ bank.get(index).getPdfLink().substring(bank.get(index).getPdfLink().lastIndexOf("/")));
}
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
String m = bank.get(index).getTitle();
manager.updateDownloadedMagazines(
Integer.parseInt(m.substring(m.lastIndexOf(" ") + 1)),
file.toString());
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
startActivity(getIntent());
finish();
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progress.setProgress(values[0]);
}
@Override
protected void onPostExecute(Long result) {
super.onPostExecute(result);
progress.setVisibility(View.INVISIBLE);
}
}
Question:
How can i implement multiple download functionality so that progress bar shows progress of each download individually??
I have defined the image view and the progress bar as final and sending these references to the AsyncTask where the magazine downloading activity is going, on click of image view.
AsyncTask spawns multiple threads and that’s how progress of each download can be updated.Code: