在imageadapter中将url数组设置为imageview

时间:2013-02-16 07:45:31

标签: android video

我在connection.connect();

遇到问题

android.os.NetworkOnMainThreadException in android

我收到此错误 如何设置asychtask到这个imageadapter 我无法在imageview中显示该网址图片

public class ImageAdapter extends BaseAdapter {
    private Context context;
    public static final String[] videos={

    "http://img.youtube.com/vi/QshNtQsiL7Y/1.jpg","http://img.youtube.com/vi/5_-tL63516w/1.jpg",
                "http://img.youtube.com/vi/CDEg9npvBa0/1.jpg"};
    private ImageView imageview;
        public ImageAdapter(Context c) {
            // TODO Auto-generated constructor stub
            context=c;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return videos.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return videos[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ImageView imageview = new ImageView(context);
            imageview.setImageBitmap(getBitmapFromURL(videos[position]));
            return imageview;
        }
        public static Bitmap getBitmapFromURL(String src) {  
            try {
                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap mybitmap = BitmapFactory.decodeStream(input);
                return mybitmap;

            } catch (Exception ex) {

                ex.printStackTrace();
                return null;
            }


        }

1 个答案:

答案 0 :(得分:0)

当应用程序尝试在HoneyComb或更高版本的主线程上执行网络操作时抛出此异常...因此,为了在列表视图中执行异步加载图像,您可以使用延迟加载概念...它有很多图书馆......请找一些链接......

https://github.com/nostra13/Android-Universal-Image-Loader

Lazy load of images in ListView

希望有所帮助