Android - 带有asynctask的Listview适配器来加载图像

时间:2014-03-21 15:53:11

标签: android listview android-asynctask

我正在尝试处理后台的图片加载。

现在,我看一下下一个链接 - here

我有一些我不明白的事情 -

1)我为listview项目制作了下一个CursorAdapter -

    public class ChatCursorAdapter extends CursorAdapter implements OnClickListener {


        public ChatCursorAdapter(Context context, Cursor c) {
            super(context, c, 0);
        }

        @Override
        public int getCount() {
            return getCursor() == null ? 0 : super.getCount();
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int _position) {
            Cursor cursor = (Cursor) getItem(_position);
            return getItemViewType(cursor);
        }

          private int getItemViewType(Cursor cursor) {
                String sender = cursor.getString(2);

                   SharedPreferences userPref = PreferenceManager
                            .getDefaultSharedPreferences(MainChat.this);


                        String saveUser =   userPref.getString("user", "");

                        if (saveUser.equalsIgnoreCase(sender)){

                            return 0;
                        }else{
                            return 1;
                        }
          }

    @Override
        public void bindView(View view, Context context, Cursor cursor) {
            holder = (ViewHolder) view.getTag();
                holder.mesg.setText(getSmiledText(MainChat.this,msg));
            holder.mesg2.setText(getSmiledText(MainChat.this,msg2));
                    holder.myImage.setTag(picPath);
             holder.myImage.setImageBitmap(setImageToImageView(picPath));

}


        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            ViewHolder holder = new ViewHolder();
            View itemLayout = null;
            switch(getItemViewType(cursor)){
            case 0:
                itemLayout = getLayoutInflater().inflate(R.layout.msg_item1,parent, false);
                break;
            case 1:
                itemLayout =  getLayoutInflater().inflate(R.layout.msg_item13, parent,false);
                break;

            }


            itemLayout.setTag(holder);
            holder.mesg = (TextView) itemLayout.findViewById(R.id.text_start);
            holder.mesg2 = (TextView) itemLayout.findViewById(R.id.text_end);
            holder.myImage = (ImageView) itemLayout.findViewById(R.id.imageView_msgpic);
            return itemLayout;


}

现在我想使用链接中的信息。

但是我不明白 - 我需要传递给AsrsorTask并在CursorAdapter中留下什么?

示例代码也使用 -

.execute(holder);

我不能像这样调用AsyncTask -

new AsyncTask().execute();

我应该如何以及在哪里调用AsyncTask,我不明白吗?

感谢您提供任何帮助

3 个答案:

答案 0 :(得分:0)

你总是可以使用像Universal-Image-Loader或Picasso这样的外部库来实现你想要做的事情=)

答案 1 :(得分:0)

看看AsyncTask。您必须覆盖doInBackground方法。您可以定义构造函数以提供要放置下载图像的视图。

public class ImageDownloader extends AsyncTask<String, Void, List<Bitmap>> {
private ImageView ivImageHolder;
private Context context;
public ImageDownloader(Context context, ImageView imageHolder) {
    this.ivImageHolder = imageHolder;
    this.context = context;
}
...
@Override
protected List<Bitmap> doInBackground(String... params) {
//This happens in background
    List<Bitmap> bitmaps = new ArrayList<Bitmap>();
    for (String url : params) {
        Bitmap bitmap = DownloadImage(url);
        bitmaps.add(bitmap);
    }
    return bitmaps;
}
....
private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return bitmap;
}
...
private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}
@Override
protected void onPostExecute(List<Bitmap> bitmaps) {
    super.onPostExecute(bitmaps);
    for (int i = 0; i < bitmaps.size(); i++) {
        final Bitmap bitmap = bitmaps.get(i);
        ivImageHolder.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new ImageViewActivity(context, bitmap).show();
            }
        });
        // iv.setImageBitmap(bitmap);
        ivImageHolder.setImageBitmap(bitmap);
        ivImageHolder.setVisibility(ImageView.VISIBLE);
    }
}

答案 2 :(得分:0)

如果你写了asyntask方法,我可以说你怎么能用它,如果它需要字符串值 你可以像这样使用:

new your_async(context).execute(url) ;

但是在我的建议中:你应该使用lazyadapter在listview上使用位图,因为如果不注意图像的属性,就会出现一个记忆问题。 这是链接:stackoverfow