如何在ListView中更新进度条。每个进度条都与通过AsyncTask完成的文件下载相关。
特性如下:
- 每个进度条都将根据下载进度进行更新。
- 当一个文件下载完成后,它将保存到SD卡中。
- 它将被添加到在后台运行的服务中。
- 当一个文件下载完成时,应该显示“已完成”(不应从ListView中删除)。
我还使用了一个数据库来下载文件。列表也依赖于数据库向量。我应该如何实现它。我也尝试过,但没有得到解决方案。
以下是两张详细描述的截图:
我也尝试了这段代码:
temp = databaseHandler.getAllNotifyNumber();
list_download = (ListView) findViewById(R.id.list_download);
myCustomAdapter = new MyCustomAdapter(mContext);
list_download.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
for (int index = 0; index < temp.size(); index++) {
String url = "http://upload.wikimedia.org/wikipedia/commons/0/05/Sna_large.png";
grabURL(url);
}
这是AsyncTask方法:
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
String filename = "MySampleFile.png";
File myFile = new File(directory, filename);
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileSize = connection.getContentLength();
InputStream is = new BufferedInputStream(url.openStream());
OutputStream os = new FileOutputStream(myFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = is.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileSize));
os.write(data, 0, count);
}
os.flush();
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
@Override
protected void onProgressUpdate(Integer... progress) {
// home_countprogress.setVisibility(View.VISIBLE);
// home_countprogress.setText(String.valueOf(progress[0]) + "%");
// progressbar_horizontal.setProgress(progress[0]);
myCustomAdapter.notifyDataSetChanged();
}
@Override
protected void onCancelled() {
Toast toast = Toast.makeText(getBaseContext(),
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
@Override
protected void onPostExecute(String filename) {
// progressbar_horizontal.setProgress(100);
// home_countprogress.setVisibility(View.VISIBLE);
}
protected void onPreExecute() {
// progressbar_horizontal.setVisibility(View.VISIBLE);
// progressbar_horizontal.setProgress(0);
// home_countprogress.setVisibility(View.VISIBLE);
myCustomAdapter = new MyCustomAdapter(mContext);
}
}