ImageLoader的不加载真实设备映像 [英] Imageloader not loading image on real device

查看:149
本文介绍了ImageLoader的不加载真实设备映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ImageLoader的类来从URL加载图像,并在显示它
列表显示。但是,这ImageLoader的加载模拟器上的形象,当我
它不加载任何图像的实际设备上运行我的应用程序。(只显示
默认图像)。

请告诉我,我有什么用ImageLoader的类做的就是它的工作在真实设备上。


  

ImageLoader的类:


 公共类ImageLoader的{    的MemoryCache的MemoryCache =新的MemoryCache();
    FileCache fileCache;
    私人地图< ImageView的,字符串> imageViews =集合
            .synchronizedMap(新的WeakHashMap< ImageView的,字符串>());
    ExecutorService的ExecutorService的;
    //处理程序,以显示在UI线程图片
    处理程序处理程序=新的处理程序();    公共ImageLoader的(上下文的背景下){
        fileCache =新FileCache(背景);
        ExecutorService的= Executors.newFixedThreadPool(5);
    }    最终诠释stub_id = R.drawable.products;    公共无效DisplayImage(字符串URL,ImageView的ImageView的){
        imageViews.put(ImageView的,URL);
        位图位图= memoryCache.get(URL);
        如果(位图!= NULL)
            imageView.setImageBitmap(位图);
        其他{
            queuePhoto(URL,ImageView的);
            imageView.setImageResource(stub_id);
        }
    }    私人无效queuePhoto(字符串URL,ImageView的ImageView的){
        PhotoToLoad P =新PhotoToLoad(URL,ImageView的);
        executorService.submit(新PhotosLoader(P));
    }    私人位图getBitmap(字符串URL){
        文件F = fileCache.getFile(URL);        位图B =去codeFILE(F);
        如果(B!= NULL)
            返回b;        从网上下载//图片
        尝试{
            位图位图= NULL;
            URL =图片网址新的URL(网址);
            HttpURLConnection的康恩=(HttpURLConnection类)图片网址
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(真);
            InputStream为= conn.getInputStream();
            OutputStream的OS =新的FileOutputStream(F);
            Utils.CopyStream(是,OS);
            os.close();
            conn.disconnect();
            位=去codeFILE(F);
            返回位图;
        }赶上(Throwable的前){
            ex.printStackTrace();
            如果(前的instanceof的OutOfMemoryError)
                memoryCache.clear();
            返回null;
        }
    }    //德$ C $连拍影像的鳞它来减少内存消耗
    私人位图德codeFILE(文件f){
        尝试{
            //德code图像尺寸
            BitmapFactory.Options O =新BitmapFactory.Options();
            o.inJustDe codeBounds = TRUE;
            的FileInputStream流1 =新的FileInputStream(F);
            BitmapFactory.de codeStream(STREAM1,空,O);
            stream1.close();            //找到正确的比例值。它应该是2的幂。
            //推荐大小512
            最终诠释REQUIRED_SIZE = 70;
            INT width_tmp = o.outWidth,height_tmp = o.outHeight;
            int标= 1;
            而(真){
                如果(width_tmp / 2'; REQUIRED_SIZE
                        || height_tmp / 2'; REQUIRED_SIZE)
                    打破;
                width_tmp / = 2;
                height_tmp / = 2;
                规模* = 2;
            }            //德code。与inSampleSize
            BitmapFactory.Options O2 =新BitmapFactory.Options();
            o2.inSampleSize =规模;
            流2的FileInputStream =新的FileInputStream(F);
            位图位图= BitmapFactory.de codeStream(流2,空,O2);
            stream2.close();
            返回位图;
        }赶上(FileNotFoundException异常五){
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回null;
    }    //任务队列
    私有类PhotoToLoad {
        公共字符串的URL;
        公共ImageView的ImageView的;        公共PhotoToLoad(字符串U,ImageView的我){
            URL = U;
            ImageView的= I;
        }
    }    类PhotosLoader实现Runnable {
        PhotoToLoad photoToLoad;        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad = photoToLoad;
        }        @覆盖
        公共无效的run(){
            尝试{
                如果(imageViewReused(photoToLoad))
                    返回;
                BMP位图= getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url,BMP);
                如果(imageViewReused(photoToLoad))
                    返回;
                BitmapDisplayer BD =新BitmapDisplayer(BMP,photoToLoad);
                handler.post(BD);
            }赶上(的Throwable日){
                th.printStackTrace();
            }
        }
    }    布尔imageViewReused(PhotoToLoad photoToLoad){
        字符串标记= imageViews.get(photoToLoad.imageView);
        如果(标记== NULL ||!tag.equals(photoToLoad.url))
            返回true;
        返回false;
    }    //用在UI线程来显示位图
    类BitmapDisplayer实现Runnable {
        位图位图;
        PhotoToLoad photoToLoad;        公共BitmapDisplayer(位图B,PhotoToLoad P){
            位= B;
            photoToLoad = P;
        }        公共无效的run(){
            如果(imageViewReused(photoToLoad))
                返回;
            如果(位图!= NULL)
                photoToLoad.imageView.setImageBitmap(位图);
            其他
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }    公共无效clearCache(){
        memoryCache.clear();
        fileCache.clear();
    }}


  

我GalleryTab类别: -


 公共类GalleryTab扩展片段{
    GridView控件GridView控件;
    ProgressDialog mProgressDialog;
    GridViewAdapter适配器;
    公开名单< GalleryList> phonearraylist = NULL;
    查看视图。
    私人的WeakReference< RemoteDataTask> asyncTaskWeakRef;    公共静态的newInstance片段(上下文的背景下){
        GalleryTab F =新GalleryTab();
        返回F;
    }    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
            捆绑savedInstanceState){
        //充气的布局该片段
        鉴于= inflater.inflate(R.layout.activity_gallery_tab,NULL);
        GridView控件=(GridView控件)view.findViewById(R.id.gridview);
        setRetainInstance(真);
        startNewAsyncTask();
        //新RemoteDataTask(本).execute();
        返回视图。
    }    // RemoteDataTask的AsyncTask
    私有类RemoteDataTask扩展的AsyncTask<太虚,太虚,太虚> {
        私人的WeakReference< GalleryTab> fragmentWeakRef;        私人RemoteDataTask(GalleryTab gallerytab){
            this.fragmentWeakRef =新的WeakReference< GalleryTab>(gallerytab);
        }        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            mProgressDialog =新ProgressDialog(getActivity());
            mProgressDialog.setTitle(库);
            mProgressDialog.setMessage(正在加载...);
            mProgressDialog.setIndeterminate(假);
            mProgressDialog.show();
        }        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            //创建数组            phonearraylist =新的ArrayList< GalleryList>();
            尝试{
                的for(int i = 0; I< = 6;我++){
                    GalleryList地图=新GalleryList();
                    map.setGallery(http://oi39.tinypic.com/21oydxs.jpg);
                    //的System.out.println(打印!!!! - + I);
                    phonearraylist.add(地图);
                }
            }赶上(ParseException的E){
                Log.e(错误,e.getMessage());
                e.printStackTrace();
            }            返回null;
        }        @覆盖
        保护无效onPostExecute(虚空结果){
            super.onPostExecute(结果);
            //如果(this.fragmentWeakRef.get()!= NULL){
            适配器=新GridViewAdapter(getActivity(),phonearraylist);
            //的System.out.println(打印尺寸 - + phonearraylist.size());
            gridview.setAdapter(适配器);            mProgressDialog.dismiss();
            //}
        }
    }    私人无效startNewAsyncTask(){
        RemoteDataTask的AsyncTask =新RemoteDataTask(本);
        this.asyncTaskWeakRef =新的WeakReference< RemoteDataTask>(AsyncTask的);
        asyncTask.execute();
    }
}


  

我GridViewAdapter类别: -


 公共类GridViewAdapter延伸BaseAdapter {    //声明变量
    上下文语境;
    LayoutInflater吹气;
    ImageLoader的ImageLoader的;
    私人列表< GalleryList> galleryArraylist = NULL;
    私人的ArrayList< GalleryList> ArrayList的;    公共GridViewAdapter(上下文的背景下,列表与LT; GalleryList> phonearraylist){
        this.context =背景;
        this.galleryArraylist = phonearraylist;
        充气= LayoutInflater.from(上下文);
        this.arraylist =新的ArrayList< GalleryList>();
        this.arraylist.addAll(phonearraylist);
        ImageLoader的=新ImageLoader的(上下文);
    }    公共类ViewHolder {
        ImageView的电话;
    }    @覆盖
    公众诠释的getCount(){
        返回galleryArraylist.size();
    }    @覆盖
    公共对象的getItem(INT位置){
        返回galleryArraylist.get(位置);
    }    @覆盖
    众长getItemId(INT位置){
        返回的位置;
    }    公共查看getView(最终诠释的立场,观点来看,一个ViewGroup父){
        最后ViewHolder持有人;
        如果(查看== NULL){
            持有人=新ViewHolder();
            鉴于= inflater.inflate(R.layout.gridview_item,NULL);
            //定位gridview_item.xml的ImageView的
            holder.phone =(ImageView的)view.findViewById(R.id.phone);
            view.setTag(保持器);
        }其他{
            支架=(ViewHolder)view.getTag();
        }
        //设置成果转化的ImageView
        imageLoader.DisplayImage(galleryArraylist.get(位置).getGallery()
                holder.phone);
        //监听GridView的项目请点击
        view.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //单个项目的点击数据发送到SingleItemView类
                意向意图=新意图(背景下,SingleItemView.class);
                //把所有的数据电话
                intent.putExtra(长廊,
                        (galleryArraylist.get(位置).getGallery()));
                //开始SingleItemView类
                context.startActivity(意向);
            }
        });
        返回视图。
    }
}


解决方案

检查清单所需的权限。

I am using ImageLoader class to load an image from an url and displaying it in a list view. But this ImageLoader is loading the image on an emulator, when I run my app on a real device it's not loading any image.(Just showing the default image).

Please tell me what I have to do with the ImageLoader class to get it working on a real device.

ImageLoader Class:

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

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

    final int stub_id = R.drawable.products;

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

    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);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            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;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            // Recommended Size 512
            final int REQUIRED_SIZE = 70;
            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;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        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() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    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();
    }

}

My GalleryTab Class:--

public class GalleryTab extends Fragment {
    GridView gridview;
    ProgressDialog mProgressDialog;
    GridViewAdapter adapter;
    public List<GalleryList> phonearraylist = null;
    View view;
    private WeakReference<RemoteDataTask> asyncTaskWeakRef;

    public static Fragment newInstance(Context context) {
        GalleryTab f = new GalleryTab();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.activity_gallery_tab, null);
        gridview = (GridView) view.findViewById(R.id.gridview);
        setRetainInstance(true);
        startNewAsyncTask();
        // new RemoteDataTask(this).execute();
        return view;
    }

    // RemoteDataTask AsyncTask
    private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        private WeakReference<GalleryTab> fragmentWeakRef;

        private RemoteDataTask(GalleryTab gallerytab) {
            this.fragmentWeakRef = new WeakReference<GalleryTab>(gallerytab);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setTitle("Gallery");
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create the array

            phonearraylist = new ArrayList<GalleryList>();
            try {
                for (int i = 0; i <= 6; i++) {
                    GalleryList map = new GalleryList();
                    map.setGallery("http://oi39.tinypic.com/21oydxs.jpg");
                    // System.out.println("PRINT!!!!--  "+ i);
                    phonearraylist.add(map);
                }
            } catch (ParseException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // if (this.fragmentWeakRef.get() != null) {
            adapter = new GridViewAdapter(getActivity(), phonearraylist);
            // System.out.println("PRINT SIZE --  "+ phonearraylist.size());
            gridview.setAdapter(adapter);

            mProgressDialog.dismiss();
            // }
        }
    }

    private void startNewAsyncTask() {
        RemoteDataTask asyncTask = new RemoteDataTask(this);
        this.asyncTaskWeakRef = new WeakReference<RemoteDataTask>(asyncTask);
        asyncTask.execute();
    }
}

My GridViewAdapter Class:-

public class GridViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ImageLoader imageLoader;
    private List<GalleryList> galleryArraylist = null;
    private ArrayList<GalleryList> arraylist;

    public GridViewAdapter(Context context, List<GalleryList> phonearraylist) {
        this.context = context;
        this.galleryArraylist = phonearraylist;
        inflater = LayoutInflater.from(context);
        this.arraylist = new ArrayList<GalleryList>();
        this.arraylist.addAll(phonearraylist);
        imageLoader = new ImageLoader(context);
    }

    public class ViewHolder {
        ImageView phone;
    }

    @Override
    public int getCount() {
        return galleryArraylist.size();
    }

    @Override
    public Object getItem(int position) {
        return galleryArraylist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.gridview_item, null);
            // Locate the ImageView in gridview_item.xml
            holder.phone = (ImageView) view.findViewById(R.id.phone);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into ImageView
        imageLoader.DisplayImage(galleryArraylist.get(position).getGallery(),
                holder.phone);
        // Listen for GridView Item Click
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data phone
                intent.putExtra("gallery",
                        (galleryArraylist.get(position).getGallery()));
                // Start SingleItemView Class
                context.startActivity(intent);
            }
        });
        return view;
    }
}

解决方案

Check necessary permissions in the manifest .

这篇关于ImageLoader的不加载真实设备映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆