2013-05-31 5 views
2

지난 며칠 동안이 문제로 어려움을 겪었습니다. 스택 오버플로에서 사용할 수있는 모든 것을 시도했지만이 문제를 해결할 수 없습니다.목록의 첫 번째 항목이 잘못되었습니다. 이미지

이 버그는 첫 번째 항목에 유효한 URL이없고 첫 번째 요소에서만 발생하는 경우에만 나타납니다. 아래로 스크롤하면 올바른 이미지가로드됩니다.

기본 아이디어는 JSON에서로드 된 이미지로 대체 될 임시 이미지를 넣는 것입니다. url (또는 invalid)이 표시되지 않으면 표시되는 동물의 유형에 따라 특정 기본값을 표시해야합니다 (개가 고양이 이미지 인 경우 개 이미지를 표시하고 고양이 이미지를 표시합니다). 여기

내가 사용하여 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에서 URL입니다 JSON에서 가져온 동물의 유형입니다.

필자는 텍스트가 정상적으로 표시되었다고 언급해야합니다. 이미지가 잘못되어 첫 번째 요소 만 (사진을 사용할 수없는 경우).

누구든지 올바른 방향으로 나를 가리킬 수 있거나 내가 잘못하고있는 것을 말해 줄 수 있다면 크게 감사하겠습니다.

편집 : 는 내가 더 이상 WeakHashMap을 사용하고지도에 각 이미지 뷰에 대한 해시 코드를 저장하지 않음으로써 문제를 해결 생각합니다.

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.hashCode(), url); 

,536,913에

imageViews.put(imageView, url); 

을 그래서 내가 변경된 것입니다 나는 이미지의 로딩 취소하는 방법 추가하여 성능에 영향을주지 않고 문제를 해결 한 :

이이 방법을 (선언

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

가 해결

에 63,210
imageViews.get(photoToLoad.imageView); 

ImageLoader에서) :

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

나는 이미지 설정 사용자 지정 ArrayAdapter와 : 당신은 통지하기 전에 어댑터 목록 또는 배열을 교체해야이 다른 사람 :

+0

코드가 현재 양식으로는 읽기가 너무 어렵습니다. 하지만 convertviews가로드되는 방법과 관련된 스레드 문제를 알려줄 수 있습니다. 스레드없이 중단 점을 사용하여 처음 실행하면 디버그가 더 명확 해집니다. – Warpzit

+0

읽을 수 없음이란 무엇입니까? 당신이 이해할 수없는 것은 무엇입니까? 아마 그것을 수정할 수 있습니다 (문제와 관련없는 몇 가지 방법을 제거하십시오)? 또한 스레드로 인해 모든 요소가 작동하지 않는다고 생각하지 않습니다. 첫 번째 요소를 제외하고는로드 할 이미지가 없을 때뿐입니다. 내 추측은 ListView 내부 Views의 재사용에 관한 것입니다 ... 위치 0에서보기 때마다 다시 그려진 테스트 및 그 방식으로 작동하는 것으로 보인다 (하지만 그것은 ListView 성능에 영향을 미치고 싶지 않아요. 그). –

+0

안녕하세요 Lonut이 문제에 대한 해결책을 얻었습니까? 같은 문제가 발생했습니다. 해결책을 찾았 으면 같은 항목을 정렬하는 데 도움주세요. – Reena

답변

0

도움이되지만됩니다

  // 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); 
     } 

희망, (언급하는 것을 잊었다) 다음 notifyDataChanged()

+0

문제를 해결하지 못했습니다. 아직도 답을 주셔서 감사합니다. –

+0

내 신청서에 어떻게 이것을 달성 할 수 있었는지 나는 생각할 수 없다. 데이터를 얻는 방법과 어댑터에서 설정하는 방법을 다시 생각해야 할 것입니다.이 같은 작은 문제에 대한 많은 작업이 있습니다 (첫 번째 항목에 대해서만 언급했는데, 심지어 빠른 스크롤 때 잘못 된 이미지가 나타나는 버그가 있습니다.) –

+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 인 경우)가 이전에 설정되었습니다 (이미지가로드 될 때까지 표시되는 임시 이미지에 문제가 없습니다. OK). 그러나 아직도 당신의 대답에 감사드립니다. –

관련 문제