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中的數據可以有效的被命中。

(五)、緩存的案例代碼:

publicclassMainActivityextendsActivity {

privatefinalstaticStringTAG="MainActivity";

privateImageViewimageView_main;

privateProgressDialogpDialog=null;

privateStringurlString="http://c.hiphotos.baidu.com/image/pic/item/5366d0160924ab18dd54473737fae6cd7b890b6b.jpg";

// private String urlString = "http://www.baidu.com/img/bdlogo.gif";

privateLruCachelruCache=null;

privateLinkedHashMap>softMap=newLinkedHashMap>();

privateHandlerhandler=newHandler() {

publicvoidhandleMessage(Message msg) {

switch(msg.what) {

case0:

pDialog.show();

break;

case1:

Bitmap bm = (Bitmap) msg.obj;

if(bm !=null) {

imageView_main.setImageBitmap(bm);

}

pDialog.dismiss();

break;

default:

break;

}

}

};

@Override

protectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

imageView_main= (ImageView) findViewById(R.id.imageView_main);

pDialog=newProgressDialog(this);

pDialog.setIcon(R.drawable.ic_launcher);

pDialog.setTitle("提示:");

pDialog.setMessage("數據加載中。。。");

//intmemClass = ((ActivityManager)

// getSystemService(Context.ACTIVITY_SERVICE))

// .getMemoryClass();

intmemoryCount = (int) Runtime.getRuntime().maxMemory();

// 獲取剩余內存的8分之一作為緩存

intcacheSize = memoryCount / 8;

Log.i(TAG,"=="+ cacheSize);

lruCache=newMyLruCache(cacheSize);// 這個初始化值是如何定義的?

}

classMyLruCacheextendsLruCache {

publicMyLruCache(intmaxSize) {

super(maxSize);

}

@Override

protectedintsizeOf(String key, Bitmap value) {

// return value.getHeight() * value.getWidth() * 4;

// Bitmap圖片的一個像素是4個字節

Log.i(TAG,"=="+ value.getByteCount());

returnvalue.getByteCount();

}

@Override

protectedvoidentryRemoved(booleanevicted, String key,

Bitmap oldValue, Bitmap newValue) {

if(evicted) {

SoftReference softReference =newSoftReference(

oldValue);

softMap.put(key, softReference);

}

}

}

publicvoidclickButton(View view) {

switch(view.getId()) {

caseR.id.button_main_submit:

Bitmap bm = getBitmapFromMemoryCache(urlString);

if(bm !=null) {

imageView_main.setImageBitmap(bm);

Log.i(TAG,"==從緩存中獲取到的圖片");

}else{

newThread(newRunnable() {

@Override

publicvoidrun() {

handler.sendEmptyMessage(0);

HttpClient httpClient =newDefaultHttpClient();

HttpGet httpGet =newHttpGet(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;

}

}

publicBitmap getBitmapFromMemoryCache(String key) {

// 1.先從強引用中獲取

Bitmap bitmap =null;

bitmap =lruCache.get(key);

if(bitmap !=null) {

Log.i(TAG,"==從強引用中找到");

returnbitmap;

}else{

// 2.如果強引用中沒有找到的話 如果軟引用中存在就將它移到強引用中 然后軟引用移除

SoftReference 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,"==從軟引用中移除");

returnbitmap;

}else{

softMap.remove(key);

}

}

}

returnnull;

}

@Override

publicbooleanonCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.next, menu);

returntrue;

}

}

二、封裝異步任務類:

(一)、AsynTaskHelper的核心代碼:

publicclassAsynTaskHelper {

privatestaticfinalStringTAG="AsynTaskHelper";

publicvoiddownloadData(String url, OnDataDownloadListener downloadListener) {

newMyTask(downloadListener).execute(url);

}

privateclassMyTaskextendsAsyncTaskbyte[]> {

privateOnDataDownloadListenerdownloadListener;

publicMyTask(OnDataDownloadListener downloadListener) {

this.downloadListener= downloadListener;

}

@Override

protectedbyte[] doInBackground(String... params) {

BufferedInputStream bis =null;

ByteArrayOutputStream baos =newByteArrayOutputStream();

try{

URL url =newURL(params[0]);

HttpURLConnection httpConn = (HttpURLConnection) url

.openConnection();

httpConn.setDoInput(true);

httpConn.setRequestMethod("GET");

httpConn.connect();

if(httpConn.getResponseCode() == 200) {

bis =newBufferedInputStream(httpConn.getInputStream());

byte[] buffer =newbyte[1024 * 8];

intc = 0;

while((c = bis.read(buffer)) != -1) {

baos.write(buffer, 0, c);

baos.flush();

}

returnbaos.toByteArray();

}

}catch(Exception e) {

e.printStackTrace();

}

returnnull;

}

@Override

protectedvoidonPostExecute(byte[] result) {

// 通過回調接口來傳遞數據

downloadListener.onDataDownload(result);

super.onPostExecute(result);

}

}

publicinterfaceOnDataDownloadListener {

voidonDataDownload(byte[] result);

}

}

三、帶有緩存的異步加載圖片類:

(一)、ImageDownloader的核心代碼:

publicclassImageDownloadHelper {

privatestaticfinalStringTAG="ImageDownloaderHelper";

privateHashMapmap=newHashMap();

privateMap>softCaches=newLinkedHashMap>();

privateLruCachelruCache=null;

publicImageDownloadHelper() {

intmemoryAmount = (int) Runtime.getRuntime().maxMemory();

// 獲取剩余內存的8分之一作為緩存

intcacheSize = memoryAmount / 8;

if(lruCache==null) {

lruCache=newMyLruCache(cacheSize);

}

Log.i(TAG,"==LruCache尺寸:"+ cacheSize);

}

/**

*

*@paramcontext

*@paramurl

*? ? ? ? ? ? 該mImageView對應的url

*@parammImageView

*@parampath

*? ? ? ? ? ? 文件存儲路徑

*@paramdownloadListener

*? ? ? ? ? ? OnImageDownload回調接口,在onPostExecute()中被調用

*/

publicvoidimageDownload(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 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 =newMyAsyncTask(context, url,

mImageView, path, downloadListener);

Log.i(TAG,"==從網絡中拿數據");

if(mImageView !=null) {

task.execute();

// 將對應的url對應的任務存起來

map.put(url, task);

}

}

}

}

}

}

/**

* 判斷是否需要重新創建線程下載圖片,如果需要,返回值為true。

*

*@paramurl

*@parammImageView

*@return

*/

privatebooleanneedCreateNewTask(ImageView mImageView) {

booleanb =true;

if(mImageView !=null) {

String curr_task_url = (String) mImageView.getTag();

if(isTasksContains(curr_task_url)) {

b =false;

}

}

returnb;

}

/**

* 檢查該url(最終反映的是當前的ImageView的tag,tag會根據position的不同而不同)對應的task是否存在

*

*@paramurl

*@return

*/

privatebooleanisTasksContains(String url) {

booleanb =false;

if(map!=null&&map.get(url) !=null) {

b =true;

}

returnb;

}

/**

* 刪除map中該url的信息,這一步很重要,不然MyAsyncTask的引用會“一直”存在于map中

*

*@paramurl

*/

privatevoidremoveTaskFromMap(String url) {

if(url !=null&&map!=null&&map.get(url) !=null) {

map.remove(url);

Log.i(TAG,"當前map的大小=="+map.size());

}

}

/**

* 從文件中拿圖片

*

*@parammActivity

*@paramimageName

*? ? ? ? ? ? 圖片名字

*@parampath

*? ? ? ? ? ? 圖片路徑

*@return

*/

privateBitmap 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 =newFile(real_path, imageName);

if(file.exists())

bitmap = BitmapFactory.decodeStream(newFileInputStream(

file));

}catch(Exception e) {

e.printStackTrace();

bitmap =null;

}

}

returnbitmap;

}

/**

* 將下載好的圖片存放到文件中

*

*@parampath

*? ? ? ? ? ? 圖片路徑

*@parammActivity

*@paramimageName

*? ? ? ? ? ? 圖片名字

*@parambitmap

*? ? ? ? ? ? 圖片

*@return

*/

privatebooleansetBitmapToFile(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 =newFile(real_path, imageName);

if(!file.exists()) {

File file2 =newFile(real_path +"/");

file2.mkdirs();

}

file.createNewFile();

FileOutputStream fos =null;

if(ImageDownloaderUtil.getInstance().hasSDCard()) {

fos =newFileOutputStream(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;

}

}

/**

* 輔助方法,一般不調用

*

*@parampath

*@parammActivity

*@paramimageName

*/

privatevoidremoveBitmapFromFile(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 =newFile(real_path, imageName);

if(file !=null)

file.delete();

}catch(Exception e) {

e.printStackTrace();

}

}

/**

* 異步下載圖片的方法

*

*@author

*

*/

privateclassMyAsyncTaskextendsAsyncTask {

privateContextcontext;

privateImageViewmImageView;

privateStringurl;

privateOnImageDownloadListenerdownloadListener;

privateStringpath;

publicMyAsyncTask(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

protectedBitmap doInBackground(String... params) {

Bitmap bm =null;

if(url!=null) {

try{

Log.i(TAG,"==訪問網絡加載圖片");

URL urlObj =newURL(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();

}

}

returnbm;

}

@Override

protectedvoidonPostExecute(Bitmap result) {

// 回調設置圖片

if(downloadListener!=null) {

downloadListener.onImageDownload(result,url);

// 該url對應的task已經下載完成,從map中將其刪除

removeTaskFromMap(url);

}

super.onPostExecute(result);

}

}

publicinterfaceOnImageDownloadListener {

voidonImageDownload(Bitmap bitmap, String imgUrl);

}

// 定義強引用緩存

classMyLruCacheextendsLruCache {

publicMyLruCache(intmaxSize) {

super(maxSize);

}

@Override

protectedintsizeOf(String key, Bitmap value) {

// return value.getHeight() * value.getWidth() * 4;

// Bitmap圖片的一個像素是4個字節

returnvalue.getByteCount();

}

@Override

protectedvoidentryRemoved(booleanevicted, String key,

Bitmap oldValue, Bitmap newValue) {

if(evicted) {

SoftReference softReference =newSoftReference(

oldValue);

softCaches.put(key, softReference);

}

}

}

staticclassImageDownloaderUtil {

privatestaticImageDownloaderUtilutil;

privateImageDownloaderUtil() {

}

publicstaticImageDownloaderUtil getInstance() {

if(util==null) {

util=newImageDownloaderUtil();

}

returnutil;

}

/**

* 判斷是否有sdcard

*

*@return

*/

publicbooleanhasSDCard() {

booleanb =false;

if(Environment.MEDIA_MOUNTED.equals(Environment

.getExternalStorageState())) {

b =true;

}

returnb;

}

/**

* 得到sdcard路徑

*

*@return

*/

publicString getExtPath() {

String path ="";

if(hasSDCard()) {

path = Environment.getExternalStorageDirectory().getPath();

}

returnpath;

}

/**

* 得到包目錄

*

*@parammActivity

*@return

*/

publicString getPackagePath(Context mActivity) {

returnmActivity.getFilesDir().toString();

}

/**

* 根據url得到圖片名

*

*@paramurl

*@return

*/

publicString getImageName(String url) {

String imageName ="";

if(url !=null) {

imageName = url.substring(url.lastIndexOf("/") + 1);

}

returnimageName;

}

}

}

(二)、應用舉例:

@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);

// 開始加載圖片

finalString 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;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,923評論 6 535
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,740評論 3 420
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,856評論 0 380
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,175評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,931評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,321評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,383評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,533評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,082評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,891評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,067評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,618評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,319評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,732評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,987評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,794評論 3 394
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,076評論 2 375

推薦閱讀更多精彩內容