Android的延迟加载不显示图像上的电话或显示与慢 [英] android lazy loading not showing images on phone or showing and is slow

查看:119
本文介绍了Android的延迟加载不显示图像上的电话或显示与慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JSON解析在线XML文档,还设有2个方法懒图像加载。下面是我的源$ C ​​$ C,说明我的问题:

说明:

方法1: 使用的AsyncTask 与行 imageLoader.DisplayImage((字符串)jsonImageText.get(IMAGELINK),活动,ImageView的); 适配器内。

方法2:

不使用的AsyncTask ,并使用try-catch块的其余部分,都不行 imageLoader.DisplayImage((字符串)jsonImageText.get( IMAGELINK),活动,ImageView的);

的问题:

方法1:

图像显示在仿真器和负载量为pretty的速度快,但他们无法显示在手机或平板电脑。

方法2:

的图像被显示在所有的仿真器和实际设备,但装载和滚动速度非常慢。

有没有什么办法来解决或者这2种方法,甚至两者的?

这是列表适配器返回ListView的行观点:

 公共类RssListAdapter扩展ArrayAdapter<的JSONObject> {

    公共ImageLoader的ImageLoader的;

    公共RssListAdapter(活动活动,列表和LT;的JSONObject> imageAndTexts){
        超级(活性,0,imageAndTexts);
        ImageLoader的=新ImageLoader的(activity.getApplicationContext());
    }


    @覆盖
    公共查看getView(INT位置,查看convertView,ViewGroup中父){

        活动活性=(活动)的getContext();
        LayoutInflater充气= activity.getLayoutInflater();

        //从充气XML的意见
        查看rowView = inflater.inflate(R.layout.image_text_layout,NULL);
        JSONObject的jsonImageText =的getItem(位置);

        TextView中的TextView =(TextView中)rowView.findViewById(R.id.job_text);
        ImageView的ImageView的=(ImageView的)rowView.findViewById(R.id.feed_image);


        尝试 {

            如果(jsonImageText.get(IMAGELINK)!= NULL){

                的System.out.println(XXXX链接找到了!);
                字符串URL =(字符串)jsonImageText.get(IMAGELINK);
                URL feedImage =新的网址(URL);

                HttpURLConnection的康恩=(HttpURLConnection类)feedImage.openConnection();
                InputStream的是= conn.getInputStream();
                位图IMG = BitmapFactory.de codeStream(是);
                imageView.setImageBitmap(IMG);

            //imageLoader.DisplayImage((String)jsonImageText.get("imageLink),活动,ImageView的);
            }

            跨区文字=(跨区)jsonImageText.get(文字);
            textView.setText(文本);

        }
        赶上(MalformedURLException的E){
            textView.setText(JSON异常);
        }

        赶上(IOException异常E){
            textView.setText(JSON异常);
        }

        赶上(JSONException E){
            textView.setText(JSON异常);
        }
        返回rowView;
    }
}
 

这是ImageLoader的类:

 公共类ImageLoader的{

    的MemoryCache的MemoryCache =新的MemoryCache();
    FileCache fileCache;
    私人地图< ImageView的,字符串> imageViews = Collections.synchronizedMap(新的WeakHashMap< ImageView的,字符串>());

    公共ImageLoader的(上下文的背景下){
        //使后台线程低优先级。这样也不会影响用户界面性能
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

        fileCache =新FileCache(上下文);
    }

    最终诠释stub_id = R.drawable.icon;
    公共无效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的)
    {
        //这个ImageView的可之前用于其它图像。所以有可能在队列一些旧的任务。我们需要将它们丢弃。
        photosQueue.Clean(ImageView的);
        PhotoToLoad P =新PhotoToLoad(URL,ImageView的);
        同步(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(对);
            photosQueue.photosToLoad.notifyAll();
        }

        //启动线程,如果它尚未开始
        如果(photoLoaderThread.getState()== Thread.State.NEW)
            photoLoaderThread.start();
    }

    私人位图getBitmap(字符串URL)
    {
        文件F = fileCache.getFile(URL);

        //从SD高速缓存
        位图B =去codeFILE(F);
        如果(B!= NULL)
            返回b;

        //从网页
        尝试 {
            点阵位图= NULL;
            URL IMAGEURL =新的网址(URL);
            HttpURLConnection的康恩=(HttpURLConnection类)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            InputStream的是= conn.getInputStream();
            的OutputStream OS =新的FileOutputStream(F);
            Utils.CopyStream(是,OS);
            os.close();
            位=去codeFILE(F);
            返回的位图;
        }赶上(例外前){
           ex.printStackTrace();
           返回null;
        }
    }

    //德$ C $连拍影像和扩展它来减少内存消耗
    私人位图德codeFILE(文件f){
        尝试 {
            //德code图像尺寸
            BitmapFactory.Options O =新BitmapFactory.Options();
            o.inJustDe codeBounds = TRUE;
            BitmapFactory.de codeStream(新的FileInputStream(f)项,空,O);

            //找到正确的比例值。它应该是2的幂。
            最终诠释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 =规模;
            返回BitmapFactory.de codeStream(新的FileInputStream(f)项,空,O2);
        }赶上(FileNotFoundException异常E){}
        返回null;
    }

    //任务队列
    私有类PhotoToLoad
    {
        公共字符串URL;
        公众的ImageView ImageView的;
        公共PhotoToLoad(字符串U,ImageView的我){
            URL = U;
            ImageView的=我;
        }
    }

    PhotosQueue photosQueue =新PhotosQueue();

    公共无效stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //照片商店列表下载
    类PhotosQueue
    {
        私人堆叠式和LT; PhotoToLoad> photosToLoad =新的堆栈< PhotoToLoad>();

        //删除这个ImageView的所有实例
        公共无效清洁(ImageView的图像)
        {
            对于(INT J = 0; J< photosToLoad.size()){
                如果(photosToLoad.get(J).imageView ==图片)
                    photosToLoad.remove(J);
                其他
                    + D];
            }
        }
    }

    类PhotosLoader继承Thread {
        公共无效的run(){
            尝试 {
                而(真)
                {
                    //线程等待直到有在队列加载任何图像
                    如果(photosQueue.photosToLoad.size()== 0)
                        同步(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    如果(photosQueue.photosToLoad.size()!= 0)
                    {
                        PhotoToLoad photoToLoad;
                        同步(photosQueue.photosToLoad){
                            photoToLoad = photosQueue.photosToLoad.pop();
                        }
                        BMP位= getBitmap(photoToLoad.url);
                        memoryCache.put(photoToLoad.url,BMP);
                        字符串变量= imageViews.get(photoToLoad.imageView);
                        如果(标记= NULL和放大器;!&安培; tag.equals(photoToLoad.url)){
                            BitmapDisplayer BD =新BitmapDisplayer(BMP,photoToLoad.imageView);
                            活动一=(活动)photoToLoad.imageView.getContext();
                            a.runOnUiThread(BD);
                        }
                    }
                    如果(Thread.interrupted())
                        打破;
                }
            }赶上(InterruptedException异常E){
                //允许线程退出
            }
        }
    }

    PhotosLoader photoLoaderThread =新PhotosLoader();

    //用于在UI线程中显示位图
    类BitmapDisplayer实现Runnable
    {
        点阵位图;
        ImageView的ImageView的;
        公共BitmapDisplayer(位图B,ImageView的我){位= B,ImageView的= I;}
        公共无效的run()
        {
            如果(位图!= NULL)
                imageView.setImageBitmap(位);
            其他
                imageView.setImageResource(stub_id);
        }
    }

    公共无效clearCache(){
        memoryCache.clear();
        fileCache.clear();
    }

}
 

解决方案

您可以尝试延迟加载图像和ListView aquery的Andr​​oid库......下面code可以帮助你......的从这里下载

  AQuery AQ =新AQuery(mContext);
aq.id(R.id.image1)图像配(http://data.whicdn.com/images/63995806/original.jpg);
 

I am using JSON to parse an online xml document and also 2 methods for lazy image loading. Below is my source code, explanation and my problem:

Explanation:

Method 1: Use AsyncTask and line imageLoader.DisplayImage((String)jsonImageText.get("imageLink"), activity, imageView); inside the adapter.

Method 2:

Not use AsyncTask and use the rest of the try-catch block and NOT the line imageLoader.DisplayImage((String)jsonImageText.get("imageLink"), activity, imageView);

The problems:

Method 1:

The images are displayed on the emulator and the loading is pretty fast, but they fail to display on a phone or a tablet.

Method 2:

The images are displayed on all the emulators and real devices, but the loading and scrolling are very slow.

Is there any way to fix either of these 2 methods or even both?

This is the list adapter which returns the ListView's row view:

public class RssListAdapter extends ArrayAdapter<JSONObject> {

    public ImageLoader imageLoader; 

    public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
        super(activity, 0, imageAndTexts);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }


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

        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();

        // Inflate the views from XML
        View rowView = inflater.inflate(R.layout.image_text_layout, null);
        JSONObject jsonImageText = getItem(position);

        TextView textView = (TextView) rowView.findViewById(R.id.job_text);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);


        try {

            if (jsonImageText.get("imageLink") != null){

                System.out.println("XXXX Link found!");
                String url = (String) jsonImageText.get("imageLink");
                URL feedImage= new URL(url);

                HttpURLConnection conn= (HttpURLConnection)feedImage.openConnection();
                InputStream is = conn.getInputStream();
                Bitmap img = BitmapFactory.decodeStream(is);
                imageView.setImageBitmap(img);

            //imageLoader.DisplayImage((String)jsonImageText.get("imageLink"), activity, imageView);
            }

            Spanned text = (Spanned)jsonImageText.get("text");
            textView.setText(text);

        }
        catch (MalformedURLException e) {
            textView.setText("JSON Exception");
        }

        catch (IOException e) {
            textView.setText("JSON Exception");
        }

        catch (JSONException e) {
            textView.setText("JSON Exception");
        }
        return rowView;
    } 
}

This is the ImageLoader class:

public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

    public ImageLoader(Context context){
        //Make the background thread low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

        fileCache=new FileCache(context);
    }

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

    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }

    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(30000);
            conn.setReadTimeout(30000);
            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=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;
            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;
        }
    }

    PhotosQueue photosQueue=new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        memoryCache.put(photoToLoad.url, bmp);
                        String tag=imageViews.get(photoToLoad.imageView);
                        if(tag!=null && tag.equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread=new PhotosLoader();

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

解决方案

you can try aquery android library for lazy loading image and listview...below code may help you..... download library from here

AQuery aq = new AQuery(mContext);
aq.id(R.id.image1).image("http://data.whicdn.com/images/63995806/original.jpg");

这篇关于Android的延迟加载不显示图像上的电话或显示与慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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