Android中的快取處理及非同步載入圖片類的封裝
一、快取介紹:
(一)、Android中快取的必要性:
智慧手機的快取管理應用非常的普遍和需要,是提高使用者體驗的有效手段之一。
1、沒有快取的弊端:
- 流量開銷:對於客戶端——伺服器端應用,從遠端獲取圖片算是經常要用的一個功能,而圖片資源往往會消耗比較大的流量。
- 載入速度:如果應用中圖片載入速度很慢的話,那麼使用者體驗會非常糟糕。
- 那麼如何處理好圖片資源的獲取和管理呢?非同步下載+本地快取
2、快取帶來的好處:
- 1. 伺服器的壓力大大減小;
- 2. 客戶端的響應速度大大變快(使用者體驗好);
- 3. 客戶端的資料加載出錯情況大大較少,大大提高了應有的穩定性(使用者體驗好);
- 4. 一定程度上可以支援離線瀏覽(或者說為離線瀏覽提供了技術支援)。
3、快取管理的應用場景:
- 1. 提供網路服務的應用;
- 2. 資料更新不需要實時更新,即便是允許3-5分鐘的延遲也建議採用快取機制;
- 3. 快取的過期時間是可以接受的(不會因為快取帶來的好處,導致某些資料因為更新不及時而影響產品的形象等)
4、大點陣圖導致記憶體開銷大的原因是什麼?
- 1.下載或載入的過程中容易導致阻塞;
- 大點陣圖Bitmap物件是png格式的圖片的30至100倍;
- 2.大點陣圖在載入到ImageView控制元件前的解碼過程;BitmapFactory.decodeFile
5、快取設計的要點:
- 1.命中率;
- 2.合理分配佔用的空間;
- 3.合理的快取層級。
(二)、載入圖片的正確流程是:“記憶體-檔案-網路 三層cache策略”
1、先從記憶體快取中獲取,取到則返回,取不到則進行下一步;
2、從檔案快取中獲取,取到則返回並更新到記憶體快取,取不到則進行下一步;
3、從網路下載圖片,並更新到記憶體快取和檔案快取。
具體說就是:同一張圖片只要從網路獲取一次,然後在本地快取起來,之後載入同一張圖片時就從快取中去載入。從記憶體快取讀取圖片是最快的,但是因為記憶體容量有限,所以最好再加上檔案快取。檔案快取空間也不是無限大的,容量越大讀取效率越低,因此可以設定一個限定大小比如10M,或者限定儲存時間比如一天。
在鍵值對(key-value)中,圖片快取的key是圖片url的hash值,value就是bitmap。所以,按照這個邏輯,只要一個url被下載過,其圖片就被快取起來了。
(三)、記憶體快取分類:
在JDK1.2以前的版本中,當一個物件不被任何變數引用,那麼程式就無法再使用這個物件。也就是說,只有物件處於可觸及狀態,程式才能使用它。這 就像在日常生活中,從商店購買了某樣物品後,如果有用,就一直保留它,否則就把它扔到垃圾箱,由清潔工人收走。一般說來,如果物品已經被扔到垃圾箱,想再 把它撿回來使用就不可能了。但有時候情況並不這麼簡單,你可能會遇到類似雞肋一樣的物品,食之無味,棄之可惜。這種物品現在已經無用了,保留它會佔空間,但是立刻扔掉它也不划算,因為也許將來還會派用場。對於這樣的可有可無的物品,一種折衷的處理辦法是:如果家裡空間足夠,就先把它保留在家裡,如果家裡空間不夠,即使把家裡所有的垃圾清除,還是無法容納那些必不可少的生活用品,那麼再扔掉這些可有可無的物品。
從JDK1.2版本開始,把物件的引用分為四種級別,從而使程式能更加靈活的控制物件的生命週期。
這四種級別由高到低依次為:強引用、軟引用、弱引用和虛引用。
下圖為物件層次的引用
1、強引用:(在Android中LruCache就是強引用快取)
平時我們程式設計的時候例如:Object object=new Object();那object就是一個強引用了。如果一個物件具有強引用,那就類似於必不可少的生活用品,垃圾回收器絕不會回收它。當記憶體空間不足,Java虛擬機器寧願丟擲OOM異常,使程式異常終止,也不會回收具有強引用的物件來解決記憶體不足問題。
2、軟引用(SoftReference):
軟引用類似於可有可無的生活用品。如果記憶體空間足夠,垃圾回收器就不會回收它,如果記憶體空間不足了,就會回收這些物件的記憶體。只要垃圾回收器沒有回收它,該物件就可以被程式使用。軟引用可用來實現記憶體敏感的快取記憶體。 軟引用可以和一個引用佇列(ReferenceQueue)聯合使用,如果軟引用所引用的物件被垃圾回收,Java虛擬機器就會把這個軟引用加入到與之關聯的引用佇列中。
使用軟引用能防止記憶體洩露,增強程式的健壯性。
3、弱引用(WeakReference):
弱引用與軟引用的區別在於:只具有弱引用的物件擁有更短暫的生命週期。在垃圾回收器執行緒掃描它所管轄的記憶體區域的過程中,一旦發現了只具有弱引用的物件,不管當前記憶體空間足夠與否,都會回收它的記憶體。不過,由於垃圾回收器是一個優先順序很低的執行緒, 因此不一定會很快發現那些只具有弱引用的物件。 弱引用可以和一個引用佇列(ReferenceQueue)聯合使用,如果弱引用所引用的物件被垃圾回收,Java虛擬機器就會把這個弱引用加入到與之關聯的引用佇列中。
4、虛引用(PhantomReference)
"虛引用"顧名思義,就是形同虛設,與其他幾種引用都不同,虛引用並不會決定物件的生命週期。如果一個物件僅持有虛引用,那麼它就和沒有任何引用一樣,在任何時候都可能被垃圾回收。 虛引用主要用來跟蹤物件被垃圾回收的活動。
虛引用與軟引用和弱引用的一個區別在於:虛引用必須和引用佇列(ReferenceQueue)聯合使用。當垃圾回收器準備回收一個物件時,如果發現它還有虛引用,就會在回收物件的記憶體之前,把這個虛引用加入到與之關聯的引用佇列中。程式可以通過判斷引用佇列中是否已經加入了虛引用,來了解被引用的物件是否將要被垃圾回收。程式如果發現某個虛引用已經被加入到引用佇列,那麼就可以在所引用的物件的記憶體被回收之前採取必要的行動。
【相關應用:】
在java.lang.ref包中提供了三個類:SoftReference類、WeakReference類和PhantomReference類,它們分別代表軟引用、弱引用和虛引用。ReferenceQueue類表示引用佇列,它可以和這三種引用類聯合使用,以便跟蹤Java虛擬機器回收所引用的對 象的活動。
Lru:Least Recently Used
近期最少使用演算法,是一種頁面置換演算法,其思想是在快取的頁面數目固定的情況下,那些最近使用次數最少的頁面將被移出,對於我們的記憶體快取來說,強引用快取大小固定為4M,如果當快取的圖片大於4M的時候,有些圖片就會被從強引用快取中刪除,哪些圖片會被刪除呢,就是那些近期使用次數最少的圖片。
(四)、記憶體儲存:
在記憶體中儲存的話,只能儲存一定的量,而不能一直往裡面放,需要設定資料的過期時間、LRU等演算法。這裡有一個方法是把常用的資料放到一個快取中(A),不常用的放到另外一個快取中(B)。當要獲取資料時先從A中去獲取,如果A中不存在那麼再去B中獲取。B中的資料主要是A中LRU出來的資料,這裡的記憶體回收主要針對B記憶體,從而保持A中的資料可以有效的被命中。
(五)、快取的案例程式碼:
publicclass MainActivity extends Activity { privatefinalstatic String TAG = "MainActivity"; private ImageView imageView_main; private ProgressDialog pDialog = null; private String urlString = "http://c.hiphotos.baidu.com/image/pic/item/5366d0160924ab18dd54473737fae6cd7b890b6b.jpg"; // private String urlString = "http://www.baidu.com/img/bdlogo.gif"; private LruCache<String, Bitmap> lruCache = null; private HashMap<String, SoftReference<Bitmap>> softMap = new HashMap<String, SoftReference<Bitmap>>(); private Handler handler = newHandler() { publicvoid handleMessage(Message msg) { switch (msg.what) { case 0: pDialog.show(); break; case 1: Bitmap bm = (Bitmap) msg.obj; if (bm != null) { imageView_main.setImageBitmap(bm); } pDialog.dismiss(); break; default: break; } } }; @Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView_main = (ImageView) findViewById(R.id.imageView_main); pDialog = new ProgressDialog(this); pDialog.setIcon(R.drawable.ic_launcher); pDialog.setTitle("提示:"); pDialog.setMessage("資料載入中。。。"); // int memClass = ((ActivityManager) // getSystemService(Context.ACTIVITY_SERVICE)) // .getMemoryClass(); int memoryCount = (int) Runtime.getRuntime().maxMemory(); // 獲取剩餘記憶體的8分之一作為快取 int cacheSize = memoryCount / 8; Log.i(TAG, "==" + cacheSize); lruCache = new MyLruCache(cacheSize);// 這個初始化值是如何定義的? } class MyLruCache extends LruCache<String, Bitmap> { public MyLruCache(int maxSize) { super(maxSize); } @Override protectedint sizeOf(String key, Bitmap value) { // return value.getHeight() * value.getWidth() * 4; // Bitmap圖片的一個畫素是4個位元組 Log.i(TAG, "==" + value.getByteCount()); return value.getByteCount();
} reference @Override protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { if (evicted) { SoftReference<Bitmap> softReference = new SoftReference<Bitmap>( oldValue); softMap.put(key, softReference); } } } publicvoid clickButton(View view) { switch (view.getId()) { case R.id.button_main_submit: Bitmap bm = getBitmapFromMemoryCache(urlString); if (bm != null) { imageView_main.setImageBitmap(bm); Log.i(TAG, "==從快取中獲取到的圖片"); } else { new Thread(new Runnable() { @Override publicvoid run() { handler.sendEmptyMessage(0); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(urlString); try { HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { byte[] data = EntityUtils.toByteArray(response .getEntity()); Log.i(TAG, "==檔案尺寸:" + data.length); Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length); // 放入強快取 lruCache.put(urlString, bm); Log.i(TAG, "==放入強快取ok"); Message msg = Message.obtain(); msg.obj = bm; msg.what = 1; handler.sendMessage(msg); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } break; default: break; } } public Bitmap getBitmapFromMemoryCache(String key) { // 1.先從強引用中獲取 Bitmap bitmap = null; bitmap = lruCache.get(key); if (bitmap != null) { Log.i(TAG, "==從強引用中找到"); return bitmap; } else { // 2.如果強引用中沒有找到的話 如果軟引用中存在就將它移到強引用中 然後軟引用移除 SoftReference<Bitmap> softReference = softMap.get(key); if (softReference != null) { bitmap = softReference.get(); Log.i(TAG, "==從軟引用中找到"); if (bitmap != null) { // 新增到強引用中 lruCache.put(key, bitmap); Log.i(TAG, "==新增到強引用中"); // 從軟引用集合中移除 softMap.remove(key); Log.i(TAG, "==從軟引用中移除"); return bitmap; } else { softMap.remove(key); } } } returnnull; } @Override publicboolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.next, menu); returntrue; } }
二、封裝非同步任務類:
(一)、AsynTaskHelper的核心程式碼:
publicclass AsynTaskHelper {
privatestaticfinal String TAG = "AsynTaskHelper";
publicvoid downloadData(String url, OnDataDownloadListener downloadListener) {
new MyTask(downloadListener).execute(url);
}
privateclass MyTask extends AsyncTask<String, Void, byte[]> {
private OnDataDownloadListener downloadListener;
public MyTask(OnDataDownloadListener downloadListener) {
this.downloadListener = downloadListener;
}
@Override
protectedbyte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = newbyte[1024 * 8];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
returnnull;
}
@Override
protectedvoid onPostExecute(byte[] result) {
// 通過回撥介面來傳遞資料
downloadListener.onDataDownload(result);
super.onPostExecute(result);
}
}
publicinterface OnDataDownloadListener {
void onDataDownload(byte[] result);
}
}
三、帶有快取的非同步載入圖片類:
(一)、ImageDownloaderHelper的核心程式碼:
publicclass ImageDownloadHelper {
privatestaticfinal String TAG = "ImageDownloaderHelper";
private HashMap<String, MyAsyncTask> map = new HashMap<String, MyAsyncTask>();
private Map<String, SoftReference<Bitmap>> softCaches = new LinkedHashMap<String, SoftReference<Bitmap>>();
private LruCache<String, Bitmap> lruCache = null;
public ImageDownloadHelper() {
int memoryAmount = (int) Runtime.getRuntime().maxMemory();
// 獲取剩餘記憶體的8分之一作為快取
int cacheSize = memoryAmount / 8;
if (lruCache == null) {
lruCache = new MyLruCache(cacheSize);
}
Log.i(TAG, "==LruCache尺寸:" + cacheSize);
}
/**
*
* @param context
* @param url
* 該mImageView對應的url
* @param mImageView
* @param path
* 檔案儲存路徑
* @param downloadListener
* OnImageDownload回撥介面,在onPostExecute()中被呼叫
*/
publicvoid imageDownload(Context context, String url,
ImageView mImageView, String path,
OnImageDownloadListener downloadListener) {
Bitmap bitmap = null;
// 先從強引用中拿資料
if (lruCache != null) {
bitmap = lruCache.get(url);
}
if (bitmap != null && url.equals(mImageView.getTag())) {
Log.i(TAG, "==從強引用中找到資料");
mImageView.setImageBitmap(bitmap);
} else {
SoftReference<Bitmap> softReference = softCaches.get(url);
if (softReference != null) {
bitmap = softReference.get();
}
// 從軟引用中拿資料
if (bitmap != null && url.equals(mImageView.getTag())) {
Log.i(TAG, "==從軟引用中找到資料");
// 新增到強引用中
lruCache.put(url, bitmap);
Log.i(TAG, "==新增到強引用中");
// 從軟引用集合中移除
softCaches.remove(url);
mImageView.setImageBitmap(bitmap);
} else {
// 從檔案快取中拿資料
String imageName = "";
if (url != null) {
imageName = ImageDownloaderUtil.getInstance().getImageName(
url);
}
bitmap = getBitmapFromFile(context, imageName, path);
if (bitmap != null && url.equals(mImageView.getTag())) {
Log.i(TAG, "==從檔案快取中找到資料");
// 放入強快取
lruCache.put(url, bitmap);
mImageView.setImageBitmap(bitmap);
} else {
// 從網路中拿資料
if (url != null && needCreateNewTask(mImageView)) {
MyAsyncTask task = new MyAsyncTask(context, url,
mImageView, path, downloadListener);
Log.i(TAG, "==從網路中拿資料");
if (mImageView != null) {
task.execute();
// 將對應的url對應的任務存起來
map.put(url, task);
}
}
}
}
}
}
/**
* 判斷是否需要重新建立執行緒下載圖片,如果需要,返回值為true。
*
* @param url
* @param mImageView
* @return
*/
privateboolean needCreateNewTask(ImageView mImageView) {
boolean b = true;
if (mImageView != null) {
String curr_task_url = (String) mImageView.getTag();
if (isTasksContains(curr_task_url)) {
b = false;
}
}
return b;
}
/**
* 檢查該url(最終反映的是當前的ImageView的tag,tag會根據position的不同而不同)對應的task是否存在
*
* @param url
* @return
*/
privateboolean isTasksContains(String url) {
boolean b = false;
if (map != null && map.get(url) != null) {
b = true;
}
return b;
}
/**
* 刪除map中該url的資訊,這一步很重要,不然MyAsyncTask的引用會“一直”存在於map中
*
* @param url
*/
privatevoid removeTaskFromMap(String url) {
if (url != null && map != null && map.get(url) != null) {
map.remove(url);
Log.i(TAG, "當前map的大小==" + map.size());
}
}
/**
* 從檔案中拿圖片
*
* @param mActivity
* @param imageName
* 圖片名字
* @param path
* 圖片路徑
* @return
*/
private Bitmap getBitmapFromFile(Context context, String imageName,
String path) {
Bitmap bitmap = null;
if (imageName != null) {
File file = null;
String real_path = "";
try {
if (ImageDownloaderUtil.getInstance().hasSDCard()) {
real_path = ImageDownloaderUtil.getInstance().getExtPath()
+ (path != null && path.startsWith("/") ? path
: "/" + path);
} else {
real_path = ImageDownloaderUtil.getInstance()
.getPackagePath(context)
+ (path != null && path.startsWith("/") ? path
: "/" + path);
}
file = new File(real_path, imageName);
if (file.exists())
bitmap = BitmapFactory.decodeStream(new FileInputStream(
file));
} catch (Exception e) {
e.printStackTrace();
bitmap = null;
}
}
return bitmap;
}
/**
* 將下載好的圖片存放到檔案中
*
* @param path
* 圖片路徑
* @param mActivity
* @param imageName
* 圖片名字
* @param bitmap
* 圖片
* @return
*/
privateboolean setBitmapToFile(String path, Context mActivity,
String imageName, Bitmap bitmap) {
File file = null;
String real_path = "";
try {
if (ImageDownloaderUtil.getInstance().hasSDCard()) {
real_path = ImageDownloaderUtil.getInstance().getExtPath()
+ (path != null && path.startsWith("/") ? path : "/"
+ path);
} else {
real_path = ImageDownloaderUtil.getInstance().getPackagePath(
mActivity)
+ (path != null && path.startsWith("/") ? path : "/"
+ path);
}
file = new File(real_path, imageName);
if (!file.exists()) {
File file2 = new File(real_path + "/");
file2.mkdirs();
}
file.createNewFile();
FileOutputStream fos = null;
if (ImageDownloaderUtil.getInstance().hasSDCard()) {
fos = new FileOutputStream(file);
} else {
fos = mActivity.openFileOutput(imageName, Context.MODE_PRIVATE);
}
if (imageName != null
&& (imageName.contains(".png") || imageName
.contains(".PNG"))) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
} else {
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
}
fos.flush();
if (fos != null) {
fos.close();
}
returntrue;
} catch (Exception e) {
e.printStackTrace();
returnfalse;
}
}
/**
* 輔助方法,一般不呼叫
*
* @param path
* @param mActivity
* @param imageName
*/
privatevoid removeBitmapFromFile(String path, Context mActivity,
String imageName) {
File file = null;
String real_path = "";
try {
if (ImageDownloaderUtil.getInstance().hasSDCard()) {
real_path = ImageDownloaderUtil.getInstance().getExtPath()
+ (path != null && path.startsWith("/") ? path : "/"
+ path);
} else {
real_path = ImageDownloaderUtil.getInstance().getPackagePath(
mActivity)
+ (path != null && path.startsWith("/") ? path : "/"
+ path);
}
file = new File(real_path, imageName);
if (file != null)
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 非同步下載圖片的方法
*
* @author
*
*/
privateclass MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
private Context context;
private ImageView mImageView;
private String url;
private OnImageDownloadListener downloadListener;
private String path;
public MyAsyncTask(Context context, String url, ImageView mImageView,
String path, OnImageDownloadListener downloadListener) {
this.context = context;
this.url = url;
this.mImageView = mImageView;
this.path = path;
this.downloadListener = downloadListener;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bm = null;
if (url != null) {
try {
Log.i(TAG, "==訪問網路載入圖片");
URL urlObj = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) urlObj
.openConnection();
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
InputStream is = httpConn.getInputStream();
bm = BitmapFactory.decodeStream(is);
}
String imageName = ImageDownloaderUtil.getInstance()
.getImageName(url);
if (!setBitmapToFile(path, context, imageName, bm)) {
removeBitmapFromFile(path, context, imageName);
}
// 放入強快取
lruCache.put(url, bm);
Log.i(TAG, "==放入強快取ok");
} catch (Exception e) {
e.printStackTrace();
}
}
return bm;
}
@Override
protectedvoid onPostExecute(Bitmap result) {
// 回撥設定圖片
if (downloadListener != null) {
downloadListener.onImageDownload(result, url);
// 該url對應的task已經下載完成,從map中將其刪除
removeTaskFromMap(url);
}
super.onPostExecute(result);
}
}
publicinterface OnImageDownloadListener {
void onImageDownload(Bitmap bitmap, String imgUrl);
}
// 定義強引用快取
class MyLruCache extends LruCache<String, Bitmap> {
public MyLruCache(int maxSize) {
super(maxSize);
}
@Override
protectedint sizeOf(String key, Bitmap value) {
// return value.getHeight() * value.getWidth() * 4;
// Bitmap圖片的一個畫素是4個位元組
return value.getByteCount();
}
@Override
protectedvoid entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) {
if (evicted) {
SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(
oldValue);
softCaches.put(key, softReference);
}
}
}
staticclass ImageDownloaderUtil {
privatestatic ImageDownloaderUtil util;
private ImageDownloaderUtil() {
}
publicstatic ImageDownloaderUtil getInstance() {
if (util == null) {
util = new ImageDownloaderUtil();
}
returnutil;
}
/**
* 判斷是否有sdcard
*
* @return
*/
publicboolean hasSDCard() {
boolean b = false;
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
b = true;
}
return b;
}
/**
* 得到sdcard路徑
*
* @return
*/
public String getExtPath() {
String path = "";
if (hasSDCard()) {
path = Environment.getExternalStorageDirectory().getPath();
}
return path;
}
/**
* 得到包目錄
*
* @param mActivity
* @return
*/
public String getPackagePath(Context mActivity) {
return mActivity.getFilesDir().toString();
}
/**
* 根據url得到圖片名
*
* @param url
* @return
*/
public String getImageName(String url) {
String imageName = "";
if (url != null) {
imageName = url.substring(url.lastIndexOf("/") + 1);
}
return imageName;
}
}
}
(二)、應用舉例:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_main, null);
viewHolder.CoverStoryImage = (ImageView) convertView.findViewById(R.id.CoverStoryImage);
viewHolder.CoverStoryName = (TextView) convertView.findViewById(R.id.CoverStoryName);
viewHolder.IssueDate = (TextView) convertView.findViewById(R.id.IssueDate);
viewHolder.Issue = (TextView) convertView.findViewById(R.id.Issue);
viewHolder.IssueYear = (TextView) convertView.findViewById(R.id.IssueYear);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.CoverStoryName.setText(dataList.get(position).get("CoverStoryName"));
viewHolder.IssueDate.setText(dataList.get(position).get("IssueDate"));
viewHolder.Issue.setText(dataList.get(position).get("Issue"));
viewHolder.IssueYear.setText(dataList.get(position).get("IssueYear"));
viewHolder.CoverStoryImage.setImageResource(R.drawable.defaultcovers);
// 開始載入圖片
final String urlString = dataList.get(position).get("CoverStoryImage");
viewHolder.CoverStoryImage.setTag(urlString);
Log.i(TAG, "settag:" + urlString);
// 方法一:增加了快取的非同步載入圖片
if (mDownloader == null) {
mDownloader = new ImageDownloader();
}
if (mDownloader != null) {
// 非同步下載圖片
mDownloader.imageDownload(urlString,
viewHolder.CoverStoryImage, "/img_temp", context,new ImageDownloader.OnImageDownload() {
@Override
public void onDownloadSuccess(Bitmap bitmap,String imgUrl, ImageView imageView) {
ImageView image_item = (ImageView) imageView.findViewWithTag(imgUrl);
if (image_item != null) {
image_item.setImageBitmap(bitmap);
image_item.setTag(null);
Log.i(TAG, "findViewWithTag:" + imgUrl);
} else {
Log.i(TAG, "imageView is null:" + imgUrl); //???為什麼會有為null的時候呢?
}
}
});
}
return convertView;
}
class ViewHolder {
private ImageView CoverStoryImage;
private TextView CoverStoryName;
private TextView IssueDate;
private TextView Issue;
private TextView IssueYear;
}