android 延迟加载未在手机上显示图像或显示速度很慢

2024-03-13

我正在使用 JSON 来解析在线 xml 文档以及两种延迟图像加载的方法。以下是我的源代码、解释和我的问题:

解释:

方法一: 使用AsyncTask和线imageLoader.DisplayImage((String)jsonImageText.get("imageLink"), activity, imageView);适配器内部。

方法二:

Not use AsyncTask并使用 try-catch 块的其余部分而不是该行imageLoader.DisplayImage((String)jsonImageText.get("imageLink"), activity, imageView);

问题:

方法一:

图像显示在模拟器上,加载速度相当快,但无法在手机或平板电脑上显示。

方法二:

图像在所有模拟器和真实设备上都显示,但加载和滚动非常慢。

有什么办法可以解决这两种方法中的任何一个或什至同时解决这两个方法吗?

这是返回 ListView 的行视图的列表适配器:

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

这是 ImageLoader 类:

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

}

你可以尝试使用aquery android库来延迟加载图像和列表视图...下面的代码可能会帮助你......从这里下载库 http://code.google.com/p/android-query/downloads/detail?name=android-query-full.0.25.10.jar

AQuery aq = new AQuery(mContext);
aq.id(R.id.image1).image("http://data.whicdn.com/images/63995806/original.jpg");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

android 延迟加载未在手机上显示图像或显示速度很慢 的相关文章

随机推荐

  • 从 ostream 获取 char* 而不进行复制

    我有一个ostream并且数据已写入其中 现在我想要该数据的形式char大批 有没有办法在不复制所有字节的情况下获取字符缓冲区及其大小 我的意思是 我知道我可以使用ostringstream并打电话str c str 但会产生一个临时副本
  • 在 SQL 中对包含数字的字符串列进行排序?

    我正在尝试对字符串列进行排序 包含数字 SELECT name FROM mytable ORDER BY name ASC name a 1 a 12 a 2 a 3 你看Mysql的自然排序算法是这样放置的a 12 after a 1
  • 从驱动器号获取驱动器型号

    我想从驱动器号中获取型号名称 例如Crucial CT256MX100SSD1是我的驱动器型号C 可以使用简单的 WMI 查询来检索模型 var hdd new ManagementObjectSearcher SELECT FROM Wi
  • 在 Ubuntu 20.04 上为 pandas 构建轮子需要 20 多分钟,但在 18.04 上不需要

    我有一个 ERPNext 的安装脚本 可以在 Ubuntu 18 04 上正常运行 当我在 20 04 上运行相同的脚本时 我不得不等待 20 多分钟才能完成 而在 18 04 上则需要大约 30 秒 我的脚本包括这两行 env bin p
  • 如何让 vim 使用正确的缩进格式化项目符号列表

    在 vim 中 我可以设置 textwidth 选项 然后将新文本格式化为换行 我还可以使用 gq 命令显式换行文本 然而 项目符号列表的行为对我来说有点出乎意料 vim 文档讨论了使用带有连字符的项目符号列表 当我尝试这样做时 它开始正常
  • router-outlet 不是已知元素

    以下代码有效 app module ts import NgModule from angular core import HttpModule from angular http import AppComponent from app
  • 如何更改此 R 图中的字体系列? [复制]

    这个问题在这里已经有答案了 我正在尝试将轴和图例的字体更改为衬线但添加family serif 没有为传奇工作 我该怎么做呢 plot sort n cdf pch 3 cex 0 5 xlab Order ylab Cn family s
  • pandas 中 groupby 中的排名

    我有一个典型的 面板数据 在计量经济学术语中 不是 pandas 面板对象 数据框有一个Date列和一个ID列 以及包含某些值的其他列 对于每个日期 我需要根据 V1 对 ID 进行横断面排名 分为 10 组 十分位数 并创建一个名为的新列
  • Python:定义特定类型对象的列表

    我想继承一个列表来生成myList类 仅接受一种特定类型的对象 例如整数 我相信装饰者可以优雅地做到这一点 使用怎么样arrays http docs python org library array html 该模块定义了一个对象类型 它
  • XLib:获取光标图像

    有没有办法使用 Xlib 检索当前光标位图 我检查过X光标人 http www xfree86 org 4 3 0 Xcursor 3 html但我没有看到任何方法可以做到这一点 使用 GetCursorImage SelectCursor
  • matlab中的支持向量机

    您能否举一个在 matlab 中使用支持向量机 SVM 进行 4 类分类的示例 例如 atribute 1 atribute 2 atribute 3 atribute 4 class 1 2 3 4 0 1 2 3 5 0 0 2 6 4
  • 如何在 Android 中使用文本视图显示颠倒的文本?

    如何在 Android 中使用文本视图显示颠倒的文本 就我而言 我有一个 2 人游戏 他们彼此面对面玩 我想向第二个面向他们的玩家展示测试 这是我在 AaronMs 建议后实施的解决方案 执行重写的类 bab foo UpsideDownT
  • Firebase 服务器时间戳将 iOS 翻倍

    ServerValue timestamp 回报 AnyHashable Any 如何将其转换为Double 这样我就可以创建一个带有时间戳的日期 这并不是 Firebase 时间戳的工作原理 它实际上所做的是将时间戳写入节点 但在写入之后
  • 如何验证 ZF2 中的复选框

    我已经阅读了许多针对 Zend Framework 缺乏默认复选框验证的解决方法 我最近开始使用 ZF2 但文档有点缺乏 有人可以演示如何使用 Zend 表单和验证机制验证复选框以确保其被选中吗 我正在为我的表单使用数组配置 使用 ZF 网
  • 安全组出口规则仅允许 ECR 请求

    当使用 ECR 存储用于 ECS 的容器映像时 EC2 实例 或 Fargate 服务 必须具有允许 通过公共互联网 访问特定于账户的存储库 URI 的安全组 许多组织都有严格的 IP 白名单规则 通常不允许为所有 IP 启用出站端口 44
  • 从命令行在 Hadoop 中检测压缩编解码器

    有没有简单的方法可以找出 Hadoop 中用于压缩文件的编解码器 我是否需要编写 Java 程序 或者将文件添加到 Hive 以便我可以使用describe formatted table 一种方法是在本地下载文件 使用hdfs dfs g
  • 具有接口的枚举类成员无法在内部找到方法

    我遇到了一个奇怪的问题 我不确定这是编译器问题还是我对接口枚举的理解 我正在使用 IntelliJ IDEA 12 构建一个 Android 项目 并且我有一个这样的类 public class ClassWithEnum private
  • Azure 服务总线序列化类型

    随着我们转向面向服务的体系结构 我们已开始研究使用 Windows Azure 服务总线来替代当前的队列 大部分文档都很清楚 但是我很难确定哪种类型的序列化BrokeredMessage当提供主体时使用 例如 假设我实例化了一个Broker
  • React:formik 表单,如何在回调函数内提交后使用状态

    我在用formik插件reactjs我想要useState表单提交后的变量 Both this and setState未定义 我无法实现它 有人可以帮我完成这件事吗 See screenshot below In JavaScript 默
  • android 延迟加载未在手机上显示图像或显示速度很慢

    我正在使用 JSON 来解析在线 xml 文档以及两种延迟图像加载的方法 以下是我的源代码 解释和我的问题 解释 方法一 使用AsyncTask和线imageLoader DisplayImage String jsonImageText