Android 使用阵列适配器在ImageView中加载图像

Android 使用阵列适配器在ImageView中加载图像,android,Android,从url在imageView中加载图像时遇到问题。图像将是高维或大尺寸的。 为此,我使用了ImageLoader函数。我也尝试过懒洋洋和毕加索。 请帮助或建议我有什么问题, 提前谢谢 这是我的适配器类 public class CustomLocalAlertAdapter extends ArrayAdapter<LocalListItem> implements AppConstants { Activity a; ViewHolder holder; @Overri

从url在
imageView
中加载图像时遇到问题。图像将是高维或大尺寸的。 为此,我使用了
ImageLoader
函数。我也尝试过懒洋洋和毕加索。 请帮助或建议我有什么问题, 提前谢谢

这是我的适配器类

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;

}
公共类CustomLocalAlertAdapter扩展了ArrayAdapter
实现AppConstants{
活动a;
视窗座;
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
//TODO自动生成的方法存根
LocalListItem LocalList=getItem(位置);
if(convertView==null){
convertView=LayoutFlater.from(getContext())。充气(
R.layout.activity\添加\本地\所有\警报\详细信息,父级,
假);
holder=新的ViewHolder();
holder.missingTitle=(TextView)convertView
.findViewById(R.id.missingTitle);
holder.missingDetails=(TextView)convertView
.findViewById(R.id.missingDetails);
holder.missingImage=(图像视图)convertView
.findViewById(R.id.missingImage);
holder.suspectImage=(图像视图)convertView
.findviewbyd(R.id.suspectImage);
//年份、品牌、型号、颜色、车牌号、Vin、地点
convertView.setTag(支架);
}否则{
holder=(ViewHolder)convertView.getTag();
}
字符串AllalertsSpectDetails=“”;
字符串allAlertVehicleDetails=“”;
字符串allAlertPersonDetails=“”;
if(LocalList.title.equalsIgnoreCase(“缺少车辆报告”)){
allAlertPersonDetails=“”;
AllalertsSpectDetails=“”;
持有人。丢失标题。setText(“丢失车辆”);
allAlertVehicleDetails=“\n”+“年:”+LocalList.Year+“\n”
+Make:“+LocalList.Make+”\n“+”模型:
+LocalList.Model+“\n”+“颜色:”+LocalList.Color
+“\n”+“LisencePlateNo:”+LocalList.LisencePlateNo
+“\n”+“Vin:”+LocalList.Vin+“\n”+“地点:”
+LocalList.Place;
holder.Tsuspectimage.setVisibility(视图已消失);
}否则{
支架.可疑图像.设置可见性(视图.可见);
allAlertVehicleDetails=“”;
持有人。遗失所有权。setText(“失踪人员”);
allAlertPersonDetails=“\n”+”名称:“+LocalList.personName
+\n“+”高度:“+LocalList.Height+”\n
+唯一标记:“+LocalList.uniqueMark+”\n
+上次查看:“+LocalList.lastSeen+”\n
+缺少日期:“+LocalList.dateMissing+”\n
+警察局:“+LocalList.policydept+”\n”
+“警察局电话:”+LocalList.policePhn+“\n”+“\n”;
if(LocalList.suspectName.equalsIgnoreCase(“”)
||LocalList.suspectName.equalsIgnoreCase(“null”)
||LocalList.suspectName.equalsIgnoreCase(“”){
AllalertsSpectDetails=“”;
holder.Tsuspectimage.setVisibility(视图已消失);
}否则{
AllalertSpectDetails=“可疑姓名:”
+LocalList.suspectName+“\n”+“车辆颜色:”
+LocalList.vehicleColor+“\n”+“车辆年份:”
+LocalList.vehicleYear+“\n”+“车辆品牌:”
+LocalList.vehicleMake+“\n”+“车辆型号:”
+LocalList.vehicleModel;
}
}
holder.missingDetails.setText(所有车辆详细信息
+allAlertPersonDetails+AllalertSpectDetails);
ImageLoader imgloader=新的ImageLoader(a.getApplicationContext());
试一试{
int loader=R.drawable.loader;
int imgURL=R.drawable.no_image_找到;
if(LocalList.title.equalsIgnoreCase(“缺少车辆报告”)){
imgloader.DisplayImage(LocalList.vehicleImg、loader、,
持有人(遗失图像);
}否则{
imgloader.DisplayImage(LocalList.personImage,loader,
持有人(遗失图像);
imgloader.DisplayImage(LocalList.suspectImage,loader,
持票人(怀疑图像);
}
}捕获(例外e){
e、 printStackTrace();
}
返回视图;
}
公共静态类视图持有者{
文本视图缺少标题;
文本视图丢失详细信息;
图像视图丢失图像;
图像视图怀疑图像;
}
公共CustomLocalAlertAdapter(上下文,
ArrayList列表项,活动a){
超级(上下文,0,列表项);
//TODO自动生成的构造函数存根
这个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();
}
公共类ImageLoader{
MemoryCache MemoryCache=新的MemoryCache();
文件缓存文件缓存;
私有地图图像视图=集合
.synchronizedMap(新WeakHashMap());
执行服务执行服务;
公共图像加载器(上下文){
fileCache=新的fileCache(上下文);
executorService=Executors.newFixedThreadPool(5);
}
int stub_id=R.drawable.ic_启动器;
public void DisplayImage(字符串url、整型加载器、ImageView){
存根id=装载机;
put(imageView,url);
位图位图=memoryCache.get(url);
if(位图!=null)
设置图像位图(位图);
否则{
队列照片(url、imageView);
setImageResource(加载程序);
}
}
私有void队列照片(字符串url,ImageView){
PhotoToLoad p=新的PhotoToLoad(url,imageView);
executorService.submit(新的PhotoLoader(p));
}
私有位图getBitmap(字符串url){
文件f=fileCache.getFile(url);
//从SD缓存
位图b=解码文件(f);
如果(b!=null)
返回b;
//从网络
试一试{
位图=空;
URL imageUrl=新URL(URL);
    <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);