使用AsyncTask在ListView中加载图片

发布于 2024-12-09 04:11:00 字数 4899 浏览 1 评论 0原文

我有一个可以保存图像的 ListView。这取决于 SDCARD 中是否存在图像。

这是我的示例代码:

public class MainActivity extends Activity  {

    ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mListView = new ListView(this);
        setContentView(mListView);

        String[] arr = new String[] { 
                "/example/images/1.jpg", "/example/images/2.jpg",  
                "/example/images/3.jpg", "/example/images/4.jpg",  
                "/example/images/5.jpg", "/example/images/6.jpg", 
                "/example/images/7.jpg", "/example/images/8.jpg",  
                "/example/images/9.jpg", "/example/images/1.jpg", 
                "/example/images/2.jpg", "/example/images/3.jpg",  
                "/example/images/4.jpg", "/example/images/5.jpg",  
                "/example/images/6.jpg", "/example/images/7.jpg",  
                "/example/images/8.jpg", "/example/images/9.jpg", 
                "/example/images/1.jpg", "/example/images/2.jpg",  
                "/example/images/3.jpg", "/example/images/4.jpg",  
                "/example/images/5.jpg", "/example/images/6.jpg", 
                "/example/images/7.jpg", "/example/images/8.jpg",  
                "/example/images/9.jpg", "/example/images/1.jpg", 
                "/example/images/2.jpg", "/example/images/3.jpg",  
                "/example/images/4.jpg", "/example/images/5.jpg",  
                "/example/images/6.jpg", "/example/images/7.jpg",  
                "/example/images/8.jpg", "/example/images/9.jpg"}; 

        List<String> list = Arrays.asList(arr);

        MyAdapter adapter = new MyAdapter(this, R.layout.listitem_imv, list);

        mListView.setAdapter(adapter);
    }

    class MyAdapter extends ArrayAdapter<String>{

        List<String> mList;
        LayoutInflater mInflater;
        int mResource;

        public MyAdapter(Context context, int resource,
                List<String> objects) {
            super(context, resource, objects);

            mResource = resource;
            mInflater = getLayoutInflater();
            mList = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;

            if(convertView == null){
                view = mInflater.inflate(mResource, null);
            }else{
                view = convertView;
            }

            ImageView imageView = (ImageView) view.findViewById(R.id.imv);
            TextView textView = (TextView) view.findViewById(R.id.txv);

                            imageView.setTag(mList.get(position));//tag of imageView == path to image
            new LoadImage().execute(imageView);
            textView.setText(mList.get(position).toString());

            return view;
        }       
    }

    class LoadImage extends AsyncTask<Object, Void, Bitmap>{

        private ImageView imv;
        private String path;


        @Override
        protected Bitmap doInBackground(Object... params) {
            imv = (ImageView)   params[0];

            path = imv.getTag().toString();

            Bitmap bitmap = null;
            File file = new File( 
                    Environment.getExternalStorageDirectory().getAbsolutePath() + path);

            if(file.exists()){
                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            }

            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            if(result != null && imv != null){
                imv.setVisibility(View.VISIBLE);
                imv.setImageBitmap(result);
            }else{
                imv.setVisibility(View.GONE);
            }
        }
    }
}

“sdcard/example/images”目录包含图像:1.jpg、2.jpg、3.jpg、4.jpg、6.jpg、7.jpg 和 9.jpg。 预期结果是: example

但是,如果我快速滚动列表,某些图像会插入到错误的项目中。 这是由于在 getView() 方法中使用 ConvertView 导致的。

如果我使用以下代码,该代码可以正常工作:

        //if(convertView == null){
        //  view = mInflater.inflate(mResource, null);
        //}else{
        //  view = convertView;
        //}
        view = mInflater.inflate(mResource, null);

当列表快速滚动时,由于使用了convertView,两个asyncTasks可以引用同一个View。 当视图不再可见时,如何取消 AsyncTask?(并且被 ListView 的另一个项目使用)

编辑

            @Override
    protected void onPostExecute(Bitmap result) {
        if(result != null && imv != null){

            if(imv.getTag().equals(path)){
                imv.setVisibility(View.VISIBLE);
                imv.setImageBitmap(result);
            }else{
                imv.setVisibility(View.GONE);
            }

        }else{
            imv.setVisibility(View.GONE);
        }
    }

I have one ListView which can hold an image. It depends if image exists or not in SDCARD.

Here my example code:

public class MainActivity extends Activity  {

    ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mListView = new ListView(this);
        setContentView(mListView);

        String[] arr = new String[] { 
                "/example/images/1.jpg", "/example/images/2.jpg",  
                "/example/images/3.jpg", "/example/images/4.jpg",  
                "/example/images/5.jpg", "/example/images/6.jpg", 
                "/example/images/7.jpg", "/example/images/8.jpg",  
                "/example/images/9.jpg", "/example/images/1.jpg", 
                "/example/images/2.jpg", "/example/images/3.jpg",  
                "/example/images/4.jpg", "/example/images/5.jpg",  
                "/example/images/6.jpg", "/example/images/7.jpg",  
                "/example/images/8.jpg", "/example/images/9.jpg", 
                "/example/images/1.jpg", "/example/images/2.jpg",  
                "/example/images/3.jpg", "/example/images/4.jpg",  
                "/example/images/5.jpg", "/example/images/6.jpg", 
                "/example/images/7.jpg", "/example/images/8.jpg",  
                "/example/images/9.jpg", "/example/images/1.jpg", 
                "/example/images/2.jpg", "/example/images/3.jpg",  
                "/example/images/4.jpg", "/example/images/5.jpg",  
                "/example/images/6.jpg", "/example/images/7.jpg",  
                "/example/images/8.jpg", "/example/images/9.jpg"}; 

        List<String> list = Arrays.asList(arr);

        MyAdapter adapter = new MyAdapter(this, R.layout.listitem_imv, list);

        mListView.setAdapter(adapter);
    }

    class MyAdapter extends ArrayAdapter<String>{

        List<String> mList;
        LayoutInflater mInflater;
        int mResource;

        public MyAdapter(Context context, int resource,
                List<String> objects) {
            super(context, resource, objects);

            mResource = resource;
            mInflater = getLayoutInflater();
            mList = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;

            if(convertView == null){
                view = mInflater.inflate(mResource, null);
            }else{
                view = convertView;
            }

            ImageView imageView = (ImageView) view.findViewById(R.id.imv);
            TextView textView = (TextView) view.findViewById(R.id.txv);

                            imageView.setTag(mList.get(position));//tag of imageView == path to image
            new LoadImage().execute(imageView);
            textView.setText(mList.get(position).toString());

            return view;
        }       
    }

    class LoadImage extends AsyncTask<Object, Void, Bitmap>{

        private ImageView imv;
        private String path;


        @Override
        protected Bitmap doInBackground(Object... params) {
            imv = (ImageView)   params[0];

            path = imv.getTag().toString();

            Bitmap bitmap = null;
            File file = new File( 
                    Environment.getExternalStorageDirectory().getAbsolutePath() + path);

            if(file.exists()){
                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            }

            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            if(result != null && imv != null){
                imv.setVisibility(View.VISIBLE);
                imv.setImageBitmap(result);
            }else{
                imv.setVisibility(View.GONE);
            }
        }
    }
}

The 'sdcard/example/images' directory has the images: 1.jpg, 2.jpg, 3.jpg, 4.jpg, 6.jpg, 7.jpg and 9.jpg.
the expected result is:
example

But, if I scroll the list quickly, some images are inserted in the wrong items.
It happens due to use of convertView in getView() method.

If I use the following code, the code works fine:

        //if(convertView == null){
        //  view = mInflater.inflate(mResource, null);
        //}else{
        //  view = convertView;
        //}
        view = mInflater.inflate(mResource, null);

When list scrolled quickly, two asyncTasks can reference one same View, due to use of convertView.
How Can I cancel AsyncTask when the View is no longer visible?(and is useb by another item of ListView)

edit

            @Override
    protected void onPostExecute(Bitmap result) {
        if(result != null && imv != null){

            if(imv.getTag().equals(path)){
                imv.setVisibility(View.VISIBLE);
                imv.setImageBitmap(result);
            }else{
                imv.setVisibility(View.GONE);
            }

        }else{
            imv.setVisibility(View.GONE);
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

錯遇了你 2024-12-16 04:11:00

您可以将 ImageView 发送到任务构造函数并在那里保留对图像路径的引用。现在,在 onPostExecute 处,检查 ImageView 的当前标记是否与您开始时使用的标记相同。如果是,则设置图像。如果不是,则不要执行任何操作。

但是,这意味着无论如何都会下载该图像。您不会在视图上设置错误的图像。

编辑:
首先将 ImageView 传递给任务构造函数:

new LoadImage(imageView).execute()

然后在 LoadImage 构造函数中保存对 ImageView 和图像路径的引用。将路径保存在构造函数中而不是保存在 doInBackground 中非常重要,以确保我们不会遇到多线程问题。然后在 onPostExecute 我们检查当前路径。

class LoadImage extends AsyncTask<Object, Void, Bitmap>{

        private ImageView imv;
        private String path;

        public LoadImage(ImageView imv) {
             this.imv = imv;
             this.path = imv.getTag().toString();
        }

    @Override
    protected Bitmap doInBackground(Object... params) {
        Bitmap bitmap = null;
        File file = new File( 
                Environment.getExternalStorageDirectory().getAbsolutePath() + path);

        if(file.exists()){
            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        }

        return bitmap;
    }
    @Override
    protected void onPostExecute(Bitmap result) {
        if (!imv.getTag().toString().equals(path)) {
               /* The path is not same. This means that this
                  image view is handled by some other async task. 
                  We don't do anything and return. */
               return;
        }

        if(result != null && imv != null){
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        }else{
            imv.setVisibility(View.GONE);
        }
    }

}

You can send in the ImageView to the task constructor and keep a reference to the image path there. Now at onPostExecute, check if the current tag of the ImageView is the same as the one that you started with. If yes, then set the image. If no, don't do anything.

However, this means that the image will be downloaded in any case. You'll just not set the wrong image on the view.

EDIT:
First pass the ImageView to the task constructor:

new LoadImage(imageView).execute()

Then save a reference to the ImageView and image path in LoadImage constructor. It is important to save the path in the constructor and not in doInBackground to ensure that we don't run into multi threading problems. Then at onPostExecute we check the current path.

class LoadImage extends AsyncTask<Object, Void, Bitmap>{

        private ImageView imv;
        private String path;

        public LoadImage(ImageView imv) {
             this.imv = imv;
             this.path = imv.getTag().toString();
        }

    @Override
    protected Bitmap doInBackground(Object... params) {
        Bitmap bitmap = null;
        File file = new File( 
                Environment.getExternalStorageDirectory().getAbsolutePath() + path);

        if(file.exists()){
            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        }

        return bitmap;
    }
    @Override
    protected void onPostExecute(Bitmap result) {
        if (!imv.getTag().toString().equals(path)) {
               /* The path is not same. This means that this
                  image view is handled by some other async task. 
                  We don't do anything and return. */
               return;
        }

        if(result != null && imv != null){
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        }else{
            imv.setVisibility(View.GONE);
        }
    }

}
守不住的情 2024-12-16 04:11:00

这篇 Android 开发者博客文章将为您提供完整的参考项目为此完成了缓存。只需将 Http 访问代码替换为 SD 卡文件读取即可。

This Android Developers Blog post will give you a complete reference project for this complete with caching. Just replace the Http access code with SD card file reads.

月亮邮递员 2024-12-16 04:11:00

我希望这有帮助。
经过大量搜索后,我有了这个可行的解决方案。

public class CustomAdapter extends ArrayAdapter<String>{
    /*
    public CustomAdapter(Context context , String[] video) {
        super(context,R.layout.custom_row, video);
    }
*/

private final Activity context;
private final String[] video;

static class ViewHolder {
    public TextView videoTitle;
    public ImageView videoThumbnail;
    public int position;
    public String path;
}

public CustomAdapter(Activity context, String[] video) {
    super(context, R.layout.custom_row, video);
    this.context = context;
    this.video = video;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater videoInflator = LayoutInflater.from(getContext());
    View customView = videoInflator.inflate(R.layout.custom_row, parent, false);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.position = position;
        viewHolder.path = video[position];
        viewHolder.videoTitle = (TextView) customView.findViewById(R.id.videoTitle);
        viewHolder.videoThumbnail = (ImageView) customView.findViewById(R.id.videoThumbnail);
        //rowView.setTag(viewHolder);
    //}
    customView.setTag(viewHolder);


    final String videoItem = video[position];
    int index=videoItem.lastIndexOf('/');
    String lastString=(videoItem.substring(index +1));
    index = lastString.indexOf(".mp4");
    lastString=(lastString.substring(0,index));
    viewHolder.videoTitle.setText(lastString);

    new AsyncTask<ViewHolder, Void, Bitmap>() {
        private ViewHolder v;

        @Override
        protected Bitmap doInBackground(ViewHolder... params) {
            v = params[0];
            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoItem, MediaStore.Images.Thumbnails.MINI_KIND);
            return thumb;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (v.position == position) {
                // If this item hasn't been recycled already, hide the
                // progress and set and show the image
                v.videoThumbnail.setImageBitmap(result);
            }
        }
    }.execute(viewHolder);
    return customView;
}

}

I hope this helps.
After lot of search I have this working solution.

public class CustomAdapter extends ArrayAdapter<String>{
    /*
    public CustomAdapter(Context context , String[] video) {
        super(context,R.layout.custom_row, video);
    }
*/

private final Activity context;
private final String[] video;

static class ViewHolder {
    public TextView videoTitle;
    public ImageView videoThumbnail;
    public int position;
    public String path;
}

public CustomAdapter(Activity context, String[] video) {
    super(context, R.layout.custom_row, video);
    this.context = context;
    this.video = video;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater videoInflator = LayoutInflater.from(getContext());
    View customView = videoInflator.inflate(R.layout.custom_row, parent, false);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.position = position;
        viewHolder.path = video[position];
        viewHolder.videoTitle = (TextView) customView.findViewById(R.id.videoTitle);
        viewHolder.videoThumbnail = (ImageView) customView.findViewById(R.id.videoThumbnail);
        //rowView.setTag(viewHolder);
    //}
    customView.setTag(viewHolder);


    final String videoItem = video[position];
    int index=videoItem.lastIndexOf('/');
    String lastString=(videoItem.substring(index +1));
    index = lastString.indexOf(".mp4");
    lastString=(lastString.substring(0,index));
    viewHolder.videoTitle.setText(lastString);

    new AsyncTask<ViewHolder, Void, Bitmap>() {
        private ViewHolder v;

        @Override
        protected Bitmap doInBackground(ViewHolder... params) {
            v = params[0];
            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoItem, MediaStore.Images.Thumbnails.MINI_KIND);
            return thumb;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (v.position == position) {
                // If this item hasn't been recycled already, hide the
                // progress and set and show the image
                v.videoThumbnail.setImageBitmap(result);
            }
        }
    }.execute(viewHolder);
    return customView;
}

}

潇烟暮雨 2024-12-16 04:11:00

也许您应该尝试:

view = mInflater.inflate(mResource,parent,null);

查看此博客,它解释了类似的问题:

http: //www.doubleencore.com/2013/05/layout-inflation-as-intending/

Maybe you should try:

view = mInflater.inflate(mResource,parent,null);

Check this blog it explains the similar issue:

http://www.doubleencore.com/2013/05/layout-inflation-as-intended/

辞旧 2024-12-16 04:11:00

我会做什么(除非你有数千张图像):
1. 创建一个数据结构 - 一个简单的类,其中包含要显示的字符串名称和位图
2.为其创建一个适配器
3.在getView方法中将正确的位图分配给正确的ImageView。

在您的情况下,您可以创建一个类似的数据结构,但不保存位图,而是保存 AsyncTask。无论如何,您需要将 asynctask 绑定到字符串到一项中。此类项目的数组(或数组列表)将被提供给您的适配器。显示的将是图像视图和文本视图。

AsyncTask 可以使用cancel() 取消。

What I would do (unless you have thousands of images):
1. create a data structure - a simple class holding a String name to be displayed and a bitmap
2. create an adapter for it
3. in the getView method assign the correct bitmap to the correct ImageView.

In your case though you can create a similar data structure but holding not a bitmap but an AsyncTask. Anyway you need to bind the asynctask to the string into one item. An array (or arraylist) of such items will be fed to your adapter. Displayed will be an imageview and a textview.

AsyncTask can be cancelled with cancel().

深海少女心 2024-12-16 04:11:00

嘿我发现这个问题的解决方案只需使用以下函数而不是你的函数

 @Override
protected void onPostExecute(Bitmap result) {

    if (!imv.getTag().toString().equals(rec_id)) {
           return;
    }

    if(result != null && imv != null){
        int index = id.indexOf(imv.getTag().toString());
        if(list.getFirstVisiblePosition()<=index && index<=list.getLastVisiblePosition())
        {
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        }
    }else{
        imv.setImageBitmap(icon);
        imv.setVisibility(View.GONE);
    }
}

这里列表是listview的对象。只需将列表视图对象传递给适配器并粘贴此函数而不是 onPostExecute 函数即可。

Hey I found the solution to this problem just use following function instead of your function

 @Override
protected void onPostExecute(Bitmap result) {

    if (!imv.getTag().toString().equals(rec_id)) {
           return;
    }

    if(result != null && imv != null){
        int index = id.indexOf(imv.getTag().toString());
        if(list.getFirstVisiblePosition()<=index && index<=list.getLastVisiblePosition())
        {
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        }
    }else{
        imv.setImageBitmap(icon);
        imv.setVisibility(View.GONE);
    }
}

Here list is the object of listview. Just pass your list view object to your adapter and paste this function instead of your onPostExecute function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文