2013-05-31 74 views
2

過去幾天我一直在努力解決這個問題。我已經嘗試了一切堆棧溢出,但我無法解決這個問題。列表中的第一個項目變得錯了圖片

只有當我的第一個項目沒有一個有效的URL並且它只發生在第一個元素時,這個錯誤纔會出現。 向下滾動後,加載了正確的圖像。

基本的想法是,我把一個臨時圖像,將被替換爲從JSON加載的圖像。如果根據我所顯示的動物的類型(如果它是一隻狗會顯示一個狗圖像,如果它是一隻貓會顯示一個貓圖像等等),沒有url(或無效)應該顯示一個特定的默認值。

這裏是在ImageLoader的類我使用的代碼:

package ro.nextlogic.petsplus.utils; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.Collections; 
import java.util.Map; 
import java.util.WeakHashMap; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

import ro.nextlogic.petsplus.R; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.util.Log; 
import android.widget.ImageView; 

public class ImageLoader { 

    static MemoryCache memoryCache=new MemoryCache(); 
    static FileCache fileCache; 
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); 
    ExecutorService executorService;  
    /** 
    * The maximum number of threads used when loading images. 
    */ 
    private static final int MAX_THREADS = 5; 
    private Context context; 

    private volatile static ImageLoader instance; 

    /** Returns singleton class instance */ 
    public static ImageLoader getInstance(Context context) { 
     if (instance == null) { 
      synchronized (ImageLoader.class) { 
       if (instance == null) { 
        instance = new ImageLoader(context); 
       } 
      } 
     } 
     return instance; 
    } 

    private ImageLoader(Context context) { 
     this.context = context; 
     fileCache=new FileCache(context); 

     executorService = Executors.newFixedThreadPool(MAX_THREADS); 
    } 

    final int stub_id = R.drawable.default_other; 
    public void displayImage(String url, ImageView imageView, final int REQUIRED_SIZE) { 
     if (url == null) { 
      return; 
     } 
     Log.i("BITMAP", "imageView = " + imageView + "\nurl = " + url); 
     imageViews.put(imageView, url); 
     Bitmap bitmap=memoryCache.get(url); 
     if (bitmap!=null && !bitmap.isRecycled()) { 
      imageView.setImageBitmap(bitmap); 
     } else { 
      queuePhoto(url, imageView, REQUIRED_SIZE); 
      imageView.setImageResource(stub_id); 
     } 
    } 

    private void queuePhoto(String url, ImageView imageView, final int REQUIRED_SIZE) { 
     PhotoToLoad p=new PhotoToLoad(url, imageView, REQUIRED_SIZE); 
     executorService.submit(new PhotosLoader(p)); 
    } 

    public static Bitmap getBitmap(final String url, final int REQUIRED_SIZE) { 
     File f = fileCache.getFile(url); 

     //from SD cache 
     Bitmap b = decodeFile(f, REQUIRED_SIZE); 
     if(b != null) 
      return b; 

     //from web 
     try { 
      Bitmap bitmap=null; 
      URL imageUrl = new URL(url); 
      HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
      conn.setConnectTimeout(30000); 
      conn.setReadTimeout(30000); 
      conn.setInstanceFollowRedirects(true); 
      InputStream is=conn.getInputStream(); 
      OutputStream os = new FileOutputStream(f); 
      Utils.CopyStream(is, os); 
      os.close(); 
      bitmap = decodeFile(f, REQUIRED_SIZE); 
      return bitmap; 
     } catch (Throwable ex){ 
      ex.printStackTrace(); 
      if(ex instanceof OutOfMemoryError) 
       memoryCache.clear(); 
      return null; 
     } 
    } 

    //decodes image and scales it to reduce memory consumption 
    private static Bitmap decodeFile(final File f, final int REQUIRED_SIZE) { 
     try { 
      // Decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      FileInputStream stream1=new FileInputStream(f); 
      BitmapFactory.decodeStream(stream1,null,o); 
      stream1.close(); 

      // The new size we want to scale to 
//   final int REQUIRED_SIZE=70; // 70 is best for Thumbnail 
      // Get the width and height of the image 
      int width_tmp=o.outWidth, height_tmp=o.outHeight; 
      // Find the correct scale value. It should be the power of 2. 
      int scale=1; 
      while(true){ 
       if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
        break; 
       width_tmp/=2; 
       height_tmp/=2; 
       scale*=2; 
      } 
      // Decode with inSampleSize 
      BitmapFactory.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize=scale; 
      FileInputStream stream2=new FileInputStream(f); 
      Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); 
      stream2.close(); 
      return bitmap; 
     } catch (FileNotFoundException e1) { 
//   Log.e("IMAGELOADER", "FileNotFoundException: ", e1); 
     } catch (IOException e2) { 
      Log.e("IMAGELOADER", "IOException: ", e2); 
     } 
     return null; 
    } 

    //Task for the queue 
    private class PhotoToLoad { 
     public final String url; 
     public final ImageView imageView; 
     public final int REQUIRED_SIZE; 
     public PhotoToLoad(final String u, final ImageView i, final int rq){ 
      url=u; 
      imageView=i; 
      REQUIRED_SIZE = rq; 
     } 
    } 

    class PhotosLoader implements Runnable { 
     PhotoToLoad photoToLoad; 
     PhotosLoader(PhotoToLoad photoToLoad) { 
      this.photoToLoad=photoToLoad; 
     } 

     @Override 
     public void run() { 
      try{ 
       if(imageViewReused(photoToLoad)) 
        return; 
       Bitmap bmp = getBitmap(photoToLoad.url, photoToLoad.REQUIRED_SIZE); 
       memoryCache.put(photoToLoad.url, bmp); 
       if(imageViewReused(photoToLoad)) 
        return; 
       BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad); 
       Activity a=(Activity)photoToLoad.imageView.getContext(); 
       a.runOnUiThread(bd); 
      }catch(Throwable th){ 
       th.printStackTrace(); 
      } 
     } 
    } 

    boolean imageViewReused(PhotoToLoad photoToLoad) { 
     String tag=imageViews.get(photoToLoad.imageView); 
     if(tag==null || !tag.equals(photoToLoad.url)) 
      return true; 
     return false; 
    } 

    //Used to display bitmap in the UI thread 
    class BitmapDisplayer implements Runnable { 
     Bitmap bitmap; 
     PhotoToLoad photoToLoad; 
     public BitmapDisplayer(Bitmap b, PhotoToLoad p) { 
      bitmap = b; 
      photoToLoad = p; 
     } 
     public void run() { 
      if(imageViewReused(photoToLoad)) 
       return; 
      if(bitmap != null) 
       Utils.imageViewAnimatedChange(context, photoToLoad.imageView, bitmap); 
//    photoToLoad.imageView.setImageBitmap(bitmap); 
     } 
    } 

    public void clearCache() { 
     memoryCache.clear(); 
     fileCache.clear(); 
    } 
} 

,這是我怎麼稱呼它:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View rowView = convertView; 
    final ViewHolder holder; 

    if (convertView == null) { 
     rowView = inflator.inflate(R.layout.shelter_animal_rowlayout, parent, false); 
     holder = new ViewHolder(); 
     holder.animalImg = (ImageView) rowView.findViewById(R.id.shelter_animal_image); 
     holder.animalName = (TextView) rowView.findViewById(R.id.shelter_animal_name); 
     holder.animalDescription = (TextView) rowView.findViewById(R.id.shelter_animal_description); 
     rowView.setTag(holder);    
    } else { 
     holder = ((ViewHolder) rowView.getTag()); 
    } 

    AnimalItem animalItem = filteredModelItemsArray.get(position); 
    if (animalItem != null) { 
     // Display the animal name, set "Unknown" if not available 
     if (!TextUtils.isEmpty(animalItem.name) &&     // Not empty 
       !animalItem.name.contains("Unknown")) {  // Not Unknown 
      holder.animalName.setText(animalItem.name); 
     } else { 
      holder.animalName.setText(R.string.shelter_animal_name); 
     } 

     // Display the animal description, set "Unknown" if not available 
     if (!TextUtils.isEmpty(animalItem.description) &&     // Not empty 
       !animalItem.description.contains("Unknown")) { // Not Unknown 
      holder.animalDescription.setText(Html.fromHtml(animalItem.description));  
     } else { 
      holder.animalDescription.setText(R.string.shelter_animal_description); 
     } 

     // Display the animal image 
     if (animalItem.photo != null) { 
      imageLoader.displayImage(animalItem.photo, holder.animalImg, 70); 
     } else if (animalItem.animal.contains("Dog")) { 
      holder.animalImg.setImageResource(R.drawable.default_dog); 
     } else if (animalItem.animal.contains("Cat")) { 
      holder.animalImg.setImageResource(R.drawable.default_cat); 
     } else { 
      holder.animalImg.setImageResource(android.R.drawable.ic_menu_help); 
     } 
    } else { 
     Toast.makeText(context, "NO animals retrieved from server!", Toast.LENGTH_LONG).show(); 
    } 

return rowView; 

}

animalItem.photo是JSON animalItem.animal網址是從JSON得到的動物的類型

我應該提到,文本顯示正常...只有圖像錯誤,並且僅適用於第一個元素(當照片不可用時)。

如果任何人可以指出我在正確的方向或告訴我做錯了將不勝感激。

編輯: 我想我不使用WeakHashMap中了,並在地圖節省每個ImageView的哈希碼固定的問題。所以這是我改變了:

private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); 

private Map<Integer, String> imageViews=Collections.synchronizedMap(new HashMap<Integer, String>()); 

以及保存和獲取的值:

imageViews.put(imageView, url); 

imageViews.put(imageView.hashCode(), url); 

imageViews.get(photoToLoad.imageView); 

imageViews.get(photoToLoad.imageView.hashCode()); 

SOLUTION: 我有固定的問題,而通過添加取消圖像的加載方法影響性能:

這是方法(聲明在ImageLoader中):

public void cancelDisplayTaskFor(ImageView imageView) { 
    imageViews.remove(imageView); 
} 

然後將調用此方法在這裏我設置圖像的定製ArrayAdapter:

  // Display the animal image 
     if (animalItem.photo != null) { 
      imageLoader.displayImage(animalItem.photo, holder.animalImg, 70); 
     } else if (animalItem.animal.contains("Dog")) { 
      imageLoader.cancelDisplayTaskFor(holder.animalImg); 
      holder.animalImg.setImageResource(R.drawable.default_dog); 
     } else if (animalItem.animal.contains("Cat")) { 
      imageLoader.cancelDisplayTaskFor(holder.animalImg); 
      holder.animalImg.setImageResource(R.drawable.default_cat); 
     } else { 
      imageLoader.cancelDisplayTaskFor(holder.animalImg); 
      holder.animalImg.setImageResource(android.R.drawable.ic_menu_help); 
     } 

希望這會幫助別人:)

+0

您的代碼目前的格式太難讀。但我可以告訴你它的一個線程問題,這也與convertviews加載的方式有關。如果您在第一次運行時使用沒有線程的斷點進行調試,它將變得更加清晰。 – Warpzit

+0

你的意思是不可讀的?你無法理解的東西?也許我可以修改它(刪除一些與問題無關的方法)?此外,我不認爲這是因爲線程,除了第一個元素,只有當它沒有要加載的圖像時,一切都工作正常。我的猜測是關於在ListView中重用視圖的問題......我在每次都在重繪的位置0處測試View,並且它似乎正在以這種方式工作(但它影響ListView的性能,我不想那)。 –

+0

嗨Lonut你有沒有得到解決這個問題我也得到同樣的問題,如果你有解決方案,那麼請幫助我解決相同的,謝謝 – Reena

回答

0

,但你必須通知之前更換適配器列表或數組(忘了提),然後notifyDataChanged()

+0

這並沒有解決這個問題。布仍然感謝你的答案。 –

+0

我想不出如何爲我的應用程序實現這一點。我將不得不重新考慮如何獲取數據以及如何將其設置在適配器中,這對於像這樣的小問題似乎有很多工作(正如我剛纔提到的,這僅僅發生在第一個項目上, t甚至有錯誤的地方,當快速滾動顯示錯誤的圖像) –

+0

我的猜測是,這是因爲我使用ListView持有人(重用行)發生。我每次都放棄第一個項目並且錯誤消失,但是我不想要這樣做,因爲它影響了ListView的性能。 –

1
// change this code inside your imageloader 


     public void run() { 
     if(imageViewReused(photoToLoad)) 
      return; 
     if(bitmap != null) 
     { 
       Utils.imageViewAnimatedChange(context, photoToLoad.imageView, bitmap); 

     } 
     else 
     { 
       imageView.setImageResource(stub_id);// so if bitmap is null it will set this default image 
     } 
    } 
+0

這並沒有解決問題。我似乎沒有找到這樣做的原因...默認圖像(如果URL無效)之前設置(我沒有問題,直到圖像加載顯示的臨時圖像 - 那些工作確定)。但還是謝謝你的回答。 –

相關問題