2016-03-04 55 views
1

我遇到了來自url的imageView中加載圖像的問題。圖像的尺寸很大或很大。 爲此,我使用了ImageLoader函數。我也試過LazyloadingPicasso。 請幫忙或建議我是什麼問題, 在此先感謝。使用陣列適配器在ImageView中加載圖像

這裏是我的適配器類,

public class CustomLocalAlertAdapter extends ArrayAdapter<LocalListItem> 
    implements AppConstants { 

Activity a; 
ViewHolder holder; 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // TODO Auto-generated method stub 

    LocalListItem LocalList = getItem(position); 

    if (convertView == null) { 
     convertView = LayoutInflater.from(getContext()).inflate(
       R.layout.activity_add_local_all_alert_details, parent, 
       false); 

     holder = new ViewHolder(); 

     holder.missingTitle = (TextView) convertView 
       .findViewById(R.id.missingTitle); 
     holder.missingDetails = (TextView) convertView 
       .findViewById(R.id.missingDetails); 
     holder.missingImage = (ImageView) convertView 
       .findViewById(R.id.missingImage); 
     holder.suspectImage = (ImageView) convertView 
       .findViewById(R.id.suspectImage); 
     // Year, Make, Model, Color, LisencePlateNo, Vin, Place 
     convertView.setTag(holder); 
    } else { 
     holder = (ViewHolder) convertView.getTag(); 
    } 
    String allAlertSuspectDetails = ""; 

    String allAlertVehicleDetails = ""; 

    String allAlertPersonDetails = ""; 

    if (LocalList.title.equalsIgnoreCase("missing_vehicle_report")) { 

     allAlertPersonDetails = ""; 
     allAlertSuspectDetails = ""; 
     holder.missingTitle.setText("Missing Vehicle"); 

     allAlertVehicleDetails = "\n" + "Year: " + LocalList.Year + "\n" 
       + "Make: " + LocalList.Make + "\n" + "Model: " 
       + LocalList.Model + "\n" + "Color: " + LocalList.Color 
       + "\n" + "LisencePlateNo: " + LocalList.LisencePlateNo 
       + "\n" + "Vin: " + LocalList.Vin + "\n" + "Place: " 
       + LocalList.Place; 

     holder.suspectImage.setVisibility(View.GONE); 

    } else { 

     holder.suspectImage.setVisibility(View.VISIBLE); 

     allAlertVehicleDetails = ""; 

     holder.missingTitle.setText("Missing Person"); 

     allAlertPersonDetails = "\n" + "Name: " + LocalList.personName 
       + "\n" + "Height: " + LocalList.height + "\n" 
       + "Unique Mark: " + LocalList.uniqueMark + "\n" 
       + "Last seen: " + LocalList.lastSeen + "\n" 
       + "Date Missing: " + LocalList.dateMissing + "\n" 
       + "Police department: " + LocalList.policeDept + "\n" 
       + "Police dept.phone: " + LocalList.policePhn + "\n" + "\n"; 


     if (LocalList.suspectName.equalsIgnoreCase("") 
       || LocalList.suspectName.equalsIgnoreCase("null") 
       || LocalList.suspectName.equalsIgnoreCase(" ")) { 
      allAlertSuspectDetails = ""; 

      holder.suspectImage.setVisibility(View.GONE); 

     } else { 
      allAlertSuspectDetails = "Suspect name: " 
        + LocalList.suspectName + "\n" + "Vehicle Color: " 
        + LocalList.vehicleColor + "\n" + "Vehicle Year: " 
        + LocalList.vehicleYear + "\n" + "Vehicle Make: " 
        + LocalList.vehicleMake + "\n" + "Vehicle Model: " 
        + LocalList.vehicleModel; 
     } 
    } 

    holder.missingDetails.setText(allAlertVehicleDetails 
      + allAlertPersonDetails + allAlertSuspectDetails); 

    ImageLoader imgloader = new ImageLoader(a.getApplicationContext()); 
    try { 

     int loader = R.drawable.loader; 
     int imgURL = R.drawable.no_image_found; 

     if (LocalList.title.equalsIgnoreCase("missing_vehicle_report")) { 

       imgloader.DisplayImage(LocalList.vehicleImg, loader, 
         holder.missingImage); 
     } else { 

       imgloader.DisplayImage(LocalList.personImage, loader, 
         holder.missingImage); 
       imgloader.DisplayImage(LocalList.suspectImage, loader, 
         holder.suspectImage);    
     } 

    } catch (Exception e) { 

     e.printStackTrace(); 
    } 
    return convertView; 

} 

public static class ViewHolder { 

    TextView missingTitle; 
    TextView missingDetails; 
    ImageView missingImage; 
    ImageView suspectImage; 
} 


public CustomLocalAlertAdapter(Context context, 
     ArrayList<LocalListItem> ListItem, Activity a) { 
    super(context, 0, ListItem); 
    // TODO Auto-generated constructor stub 
    this.a = a; 

} 

}

下面是ImageLoader的功能,

public class ImageLoader { 


MemoryCache memoryCache = new MemoryCache(); 
FileCache fileCache; 
private Map<ImageView, String> imageViews = Collections 
     .synchronizedMap(new WeakHashMap<ImageView, String>()); 
ExecutorService executorService; 

public ImageLoader(Context context) { 
    fileCache = new FileCache(context); 
    executorService = Executors.newFixedThreadPool(5); 
} 

int stub_id = R.drawable.ic_launcher; 

public void DisplayImage(String url, int loader, ImageView imageView) { 
    stub_id = loader; 
    imageViews.put(imageView, url); 
    Bitmap bitmap = memoryCache.get(url); 
    if (bitmap != null) 
     imageView.setImageBitmap(bitmap); 
    else { 
     queuePhoto(url, imageView); 
     imageView.setImageResource(loader); 
    } 
} 

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

private Bitmap getBitmap(String url) { 
    File f = fileCache.getFile(url); 

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

    // from web 
    try { 
     Bitmap bitmap = null; 
     URL imageUrl = new URL(url); 
     HttpURLConnection conn = (HttpURLConnection) imageUrl 
       .openConnection(); 
     conn.setConnectTimeout(70000); 
     conn.setReadTimeout(100000); 
     conn.setInstanceFollowRedirects(true); 
     InputStream is = conn.getInputStream(); 
     OutputStream os = new FileOutputStream(f); 
     Utils.CopyStream(is, os); 
     os.close(); 
     bitmap = decodeFile(f); 
     return bitmap; 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
     return null; 
    } 
} 

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

     // Find the correct scale value. It should be the power of 2. 
     final int REQUIRED_SIZE = 40; 
     int width_tmp = o.outWidth, height_tmp = o.outHeight; 
     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; 
     return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
    } catch (FileNotFoundException e) { 
    } 
    return null; 
} 

// Task for the queue 
private class PhotoToLoad { 
    public String url; 
    public ImageView imageView; 

    public PhotoToLoad(String u, ImageView i) { 
     url = u; 
     imageView = i; 
    } 
} 

class PhotosLoader implements Runnable { 
    PhotoToLoad photoToLoad; 

    PhotosLoader(PhotoToLoad photoToLoad) { 
     this.photoToLoad = photoToLoad; 
    } 

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

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) 
      photoToLoad.imageView.setImageBitmap(bitmap); 
     else 
      photoToLoad.imageView.setImageResource(stub_id); 
    } 
} 

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

}

+0

什麼問題你面對你的代碼? –

+0

圖像未正確加載,有時圖像沒有以正確的索引顯示,有時圖像可見,但片刻後圖像消失。 @ Vivek Mishra –

回答

0

聽起來像是你有一個緩存的問題。很難弄清楚問題出在哪裏。嘗試使用Google的Volley代替。你只需要幾行代碼,它會爲你處理你的緩存。看看this的答案。

編輯:

首先進口排球庫。然後:

與NetworkImageView替換的ImageView:

<com.android.volley.toolbox.NetworkImageView 
    android:id="@+id/networkImageView" 
    android:layout_width="150dp" 
    android:layout_height="170dp" 
    android:layout_centerHorizontal="true" /> 

這是你如何設置圖像:

// Get the NetworkImageView that will display the image. 
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView); 

ImageView mImageView; 
String url = "http://i.imgur.com/7spzG.png"; 

// Retrieves an image specified by the URL, displays it in the UI. 
ImageRequest request = new ImageRequest(url, 
new Response.Listener<Bitmap>() { 
    @Override 
    public void onResponse(Bitmap bitmap) { 
     mImageView.setImageBitmap(bitmap); 
    } 
}, 0, 0, null, 
new Response.ErrorListener() { 
    public void onErrorResponse(VolleyError error) { 
     mImageView.setImageResource(R.drawable.image_load_error); 
    } 
}); 
// Get the ImageLoader through your singleton class. 
mImageLoader = MySingleton.getInstance(this).getImageLoader(); 

// Set the URL of the image that should be loaded into this view, and 
// specify the ImageLoader that will be used to make the request. 
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader); 
相關問題