1
從doInBackground中的數組列表中讀取圖像url使用for循環,但循環不增加只有第1個url正在加載和保存圖像。這裏是代碼:for循環不會在異步任務中的Doinbackground中增加
class DownloadImageTask extends AsyncTask<Void, Void, Bitmap> {
// This class definition states that DownloadImageTask will take String
// parameters, publish Integer progress updates, and return a Bitmap
@SuppressWarnings("unused")
protected Bitmap doInBackground(Void... paths) {
//URL url;
try {
for(int j=0; j<List.size();j++)
{
reviewImageLink =List.get(j).get(TAG_Image);
URL url = new URL(reviewImageLink);
// URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink .lastIndexOf("/") + 1,reviewImageLink.length());
//try {
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
//new DownloadImageTask().execute();
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources().getString(R.string.directory));
//if(!sdImageMainDirectory.exists()){
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");}
//}
// catch (MalformedURLException e) {
// Log.v(TAG, e.toString()); }
// }
// }//try
// catch (Exception e) {
// e.printStackTrace();}
//url = new URL(List.get(j).get(TAG_Image));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length/(double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);
} else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length- downloaded);
} else {
read = is.read(imageData, downloaded, buffersize);
}
downloaded += read;
setProgress((downloaded * 100)/length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
}
}catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1,reviewImageLink.length());
if (result != null) {
hasExternalStoragePublicPicture(name);
saveToSDCard(result, name);
isImage = true;
} else {
isImage = false;
}
}
}
我認爲'返回位圖;'打破循環 – 2013-02-25 07:08:07
不知何故,我認爲List.size()很奇怪,是不是一個類,而不是一個對象? – Gjordis 2013-02-25 07:10:37
@ρяσѕρєяK是的,當我評論返回位圖;語句循環運行良好,但我可以在哪裏返回? – 2013-02-25 08:33:04