Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从JSON数组下载图像并显示在ViewPager中_Android_Image_Slider_Android Viewpager - Fatal编程技术网

Android 从JSON数组下载图像并显示在ViewPager中

Android 从JSON数组下载图像并显示在ViewPager中,android,image,slider,android-viewpager,Android,Image,Slider,Android Viewpager,我正在尝试使用ViewPager制作图像滑块。 将有图像url数组。我想下载这些图像并将其显示在ViewPager中。 我已经浏览了一些链接,但没有找到适合我的问题的解决方案。 有人能帮我吗? 提前感谢。package com.app.cr.cache; package com.app.cr.cache; import java.io.File; import java.io.FileDescriptor; import java.io.FileInpu

我正在尝试使用ViewPager制作图像滑块。 将有图像url数组。我想下载这些图像并将其显示在ViewPager中。 我已经浏览了一些链接,但没有找到适合我的问题的解决方案。 有人能帮我吗? 提前感谢。

package com.app.cr.cache;
        package com.app.cr.cache;

    import java.io.File;
    import java.io.FileDescriptor;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.channels.FileChannel;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Random;
    import java.util.WeakHashMap;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.atomic.AtomicBoolean;

    import android.app.Activity;
    import android.content.ContentUris;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.net.Uri;
    import android.os.Handler;
    import android.os.ParcelFileDescriptor;
    import android.util.SparseArray;
    import android.util.SparseIntArray;

    import com.app.cr.R;
    import com.app.cr.ui.ImageViewProgress;
    import com.app.cr.utility.Utility;

    public class ImageLoader {

        public MemoryCache memoryCache = new MemoryCache();
        public FileCache fileCache;
        private Map<ImageViewProgress, String> imageViews = Collections
                .synchronizedMap(new WeakHashMap<ImageViewProgress, String>());
        ExecutorService executorService;
        Handler handler = new Handler();
        private Activity context;

        static final int default_image = R.drawable.transparent;
        static final int[] color = new int[] { R.color.first, R.color.second,
                R.color.third, R.color.fourth, R.color.fifth, R.color.six,
                R.color.seven, R.color.eight };
        SparseArray<Bitmap> sparseArrayBitmap = new SparseArray<>();
        SparseIntArray sparseArrayInt = new SparseIntArray();

        private AtomicBoolean paused = new AtomicBoolean(false);
        private Object pauseLock = new Object();

        public ImageLoader(Activity context) {
            this.context = context;
            fileCache = new FileCache(context);
            executorService = Executors.newFixedThreadPool(3);
        }

        public void displayImageResource(int resourceId, ImageViewProgress imageView) {
            imageView.setImageResource(resourceId);
            imageView.showImage(true);
        }

        public void displayImageUri(Uri uri, ImageViewProgress imageView) {
            if (uri == null) {
                imageView.setImageResource(R.drawable.ic_people);
                imageView.showImage(true);
                return;
            }
            imageView.setImageUri(uri);
            imageView.showImage(true);
        }

        public void displayImage(String url, ImageViewProgress imageView) {
            if (url == null || url.length() == 0) {
                Utility.log("ImageLoader", "url length zero");
                if (imageView != null) {
                    imageView.showImage(false);
                }
                return;
            }

            imageViews.put(imageView, url);
            Bitmap bitmap = memoryCache.get(url);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                if (sparseArrayInt.get(url.hashCode()) != 0) {
                    Bitmap b = sparseArrayBitmap.get(sparseArrayInt.get(url
                            .hashCode()));
                    if (b != null) {
                        imageView.setImageBitmap(b);
                        return;
                    }
                }
                queuePhoto(url, imageView);
                imageView.setImageResource(default_image);
                imageView.showImage(false);
            }
        }

        private void queuePhoto(String url, ImageViewProgress imageView) {
            PhotoToLoad p = new PhotoToLoad(url, imageView);
            executorService.submit(new PhotosLoader(p));
        }

        // Task for the queue
        private class PhotoToLoad {
            public String url;
            public ImageViewProgress imageView;

            public PhotoToLoad(String u, ImageViewProgress i) {
                url = u;
                imageView = i;
            }
        }

        class PhotosLoader implements Runnable {
            PhotoToLoad photoToLoad;

            PhotosLoader(PhotoToLoad photoToLoad) {
                this.photoToLoad = photoToLoad;
            }

            @Override
            public void run() {
                if (waitIfPaused())
                    return;

                try {
                    if (imageViewReused(photoToLoad))
                        return;
                    Bitmap bmp = getBitmap(photoToLoad.url);
                    if (imageViewReused(photoToLoad))
                        return;
                    BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                    handler.post(bd);
                } catch (Throwable th) {
                    th.printStackTrace();
                }
            }
        }

        private boolean waitIfPaused() {
            AtomicBoolean pause = getPaused();
            if (pause.get()) {
                synchronized (getPauseLock()) {
                    if (pause.get()) {
                        try {
                            getPauseLock().wait();
                        } catch (InterruptedException e) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public Bitmap getBitmap(String url) {
            File f = FileCache.getFile(url);
            Bitmap b = decodeFile(f, false);
            if (b != null) {
                memoryCache.put(url, b);
                return b;
            } else {
                return getColourBitmap(url);
            }
        }

        int lastColorId = 0;

        private int getRandomColor() {
            int colorId = color[new Random().nextInt(color.length)];
            if (lastColorId == colorId) {
                colorId = getRandomColor();
            }
            lastColorId = colorId;
            return colorId;
        }

        private Bitmap getColourBitmap(String url) {
            int colorId = getRandomColor();

            sparseArrayInt.put(url.hashCode(), colorId);

            Bitmap bitmap = sparseArrayBitmap.get(colorId);
            if (bitmap == null) {
                sparseArrayBitmap.put(colorId, makeColorFillBitmap(colorId));
                bitmap = sparseArrayBitmap.get(colorId);
            }

            Utility.log("color :" + colorId, " hash : " + url.hashCode());
            if (bitmap == null) {
                return makeColorFillBitmap(colorId);
            } else {
                return bitmap;
            }
        }

        private Bitmap makeColorFillBitmap(int color) {
            int width = 150;
            int height = 150;

            Bitmap outBitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(outBitmap);
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(context.getResources().getColor(color));
            canvas.drawRect(0, 0, width, height, paint);

            return outBitmap;
        }

        public static Bitmap decodeFile(File f, boolean useForFileCheck) {
            if (f == null || !f.exists()) {
                return null;
            }

            try {
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                FileInputStream stream1 = new FileInputStream(f);
                BitmapFactory.decodeStream(stream1, null, o);
                stream1.close();
                final int REQUIRED_SIZE = 160;

                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;
                }
                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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        boolean imageViewReused(PhotoToLoad photoToLoad) {
            String tag = imageViews.get(photoToLoad.imageView);
            if (tag == null || !tag.equals(photoToLoad.url))
                return true;
            return false;
        }

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

        public void clearCache() {

            if (imageViews != null) {
                imageViews.clear();
            }

            Map<String, Bitmap> cache = memoryCache.getCache();
            Iterator<Entry<String, Bitmap>> entries = cache.entrySet().iterator();
            while (entries.hasNext()) {
                Entry<String, Bitmap> thisEntry = (Entry<String, Bitmap>) entries
                        .next();
                Bitmap value = (Bitmap) thisEntry.getValue();
                if (value != null) {
                    value.recycle();
                    value = null;
                }
                entries.remove();
            }

            memoryCache.clear();
            // fileCache.clear();
            if (sparseArrayBitmap != null) {
                sparseArrayBitmap.clear();
            }
            if (sparseArrayInt != null) {
                sparseArrayInt.clear();
            }
            Utility.log("===Memory Cache===", "All Cleared.");
        }

        public static boolean getAlbumart(File f, Long album_id, Activity activity) {
            try {

                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }

                final Uri sArtworkUri = Uri
                        .parse("content://media/external/audio/albumart");

                Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);

                ParcelFileDescriptor pfd = activity.getContentResolver()
                        .openFileDescriptor(uri, "r");

                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    copyFdToFile(fd, f);
                }

                if (f != null && f.exists()) {
                    if (bitmap.isRecycled()) {
                        bitmap = decodeFile(f, false);

                        FileOutputStream outputStream = null;
                        try {
                            outputStream = new FileOutputStream(f);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                    outputStream);
                        } catch (Exception e) {
                        } finally {
                            if (outputStream != null) {
                                outputStream.flush();
                                outputStream.close();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                return false;
            }
            return true;
        }

        private static Bitmap bitmap = null;

        public static void copyFdToFile(FileDescriptor src, File dst)
                throws IOException {

            FileChannel inChannel = new FileInputStream(src).getChannel();
            FileChannel outChannel = new FileOutputStream(dst).getChannel();
            try {
                inChannel.transferTo(0, inChannel.size(), outChannel);
            } finally {
                if (inChannel != null)
                    inChannel.close();
                if (outChannel != null)
                    outChannel.close();
            }
        }

        public void onPaused() {
            paused.set(true);
        }

        public void onResumed() {
            paused.set(false);
            synchronized (pauseLock) {
                pauseLock.notifyAll();
            }
        }

        public AtomicBoolean getPaused() {
            return paused;
        }

        public void setPaused(AtomicBoolean paused) {
            this.paused = paused;
        }

        public Object getPauseLock() {
            return pauseLock;
        }

        public void setPauseLock(Object pauseLock) {
            this.pauseLock = pauseLock;
        }
    }


package com.app.cr.cache;

import java.io.File;

import android.content.Context;

public class FileCache {

    public static File cacheDir;

    public FileCache(Context context) {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(
                    android.os.Environment.getExternalStorageDirectory(),
                    "Player");
        } else {
            cacheDir = context.getCacheDir();
        }

        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }

    public static File getFile(String url) {
        String filename = String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        return f;
    }

    public static File getFileAbsoluteFileName(String url) {
        File f = new File(cacheDir, url);
        return f;
    }

    public void clear() {
        File[] files = cacheDir.listFiles();
        if (files == null)
            return;
        for (File f : files)
            f.delete();
    }

}



package com.app.cr.cache;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.app.cr.utility.Utility;

public class MemoryCache {

    private static final String TAG = "MemoryCache.java";

    private Map<String, Bitmap> cache = Collections
            .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));

    private LruCache<String, Bitmap> lruCache = null;

    private long size = 0;
    private long limit = 1000000;

    public MemoryCache() {
        setLimit(Runtime.getRuntime().maxMemory() / 8);
        lruCache = new LruCache<String, Bitmap>((int) Runtime.getRuntime()
                .maxMemory() / 8) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return getBitmapSize(value);
            }
        };
    }

    public Map<String, Bitmap> getCache() {
        return cache;
    }

    public void setLimit(long new_limit) {
        limit = new_limit;
        Utility.log(TAG, "MemoryCache will use up to " + limit / 1024. / 1024.
                + "MB");
    }

    public synchronized Bitmap get(String id) {
        if (lruCache != null) {
            final Bitmap memBitmap = lruCache.get(id);
            if (memBitmap != null) {
                return memBitmap;
            }
        }

        try {
            if (!cache.containsKey(id))
                return null;
            return cache.get(id);
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public synchronized void put(String id, Bitmap bitmap) {
        if (id == null || bitmap == null) {
            return;
        }

        // Add to memory cache
        if (lruCache != null && lruCache.get(id) == null) {
            lruCache.put(id, bitmap);
            return;
        }

        try {
            if (cache.containsKey(id))
                size -= getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size += getSizeInBytes(bitmap);
            checkSize();
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

    public static int getBitmapSize(Bitmap bitmap) {
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    private synchronized void checkSize() {
        // Utility.log(TAG, "cache size=" + size + " length=" + cache.size());
        if (size > limit) {
            Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Bitmap> entry = iter.next();
                size -= getSizeInBytes(entry.getValue());
                iter.remove();
                if (size <= limit)
                    break;
            }
            // Utility.log(TAG, "Clean cache. New size " + cache.size());
        }
    }

    public void clear() {
        try {
            if (lruCache != null)
                lruCache.evictAll();

            cache.clear();
            size = 0;
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }
    }

    long getSizeInBytes(Bitmap bitmap) {
        if (bitmap == null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}
导入java.io.File; 导入java.io.FileDescriptor; 导入java.io.FileInputStream; 导入java.io.FileNotFoundException; 导入java.io.FileOutputStream; 导入java.io.IOException; 导入java.nio.channels.FileChannel; 导入java.util.Collections; 导入java.util.Iterator; 导入java.util.Map; 导入java.util.Map.Entry; 导入java.util.Random; 导入java.util.WeakHashMap; 导入java.util.concurrent.ExecutorService; 导入java.util.concurrent.Executors; 导入java.util.concurrent.AtomicBoolean; 导入android.app.Activity; 导入android.content.ContentUris; 导入android.graphics.Bitmap; 导入android.graphics.BitmapFactory; 导入android.graphics.Canvas; 导入android.graphics.Paint; 导入android.net.Uri; 导入android.os.Handler; 导入android.os.ParcelFileDescriptor; 导入android.util.SparseArray; 导入android.util.SparseIntArray; 导入com.app.cr.R; 导入com.app.cr.ui.ImageViewProgress; 导入com.app.cr.utility.utility; 公共类图像加载器{ public MemoryCache MemoryCache=新的MemoryCache(); 公共文件缓存文件缓存; 私有地图图像视图=集合 .synchronizedMap(新WeakHashMap()); 执行服务执行服务; Handler=newhandler(); 私人活动语境; 静态最终int default_image=R.drawable.transparent; 静态最终int[]color=新int[]{R.color.first,R.color.second, 第三,第四,第五,第六, R.color.seven,R.color.seight}; SparseArray SparseArray位图=新SparseArray(); SparseIntArray sparseArrayInt=新SparseIntArray(); 私有AtomicBoolean暂停=新的AtomicBoolean(false); 私有对象pauseLock=新对象(); 公共图像加载器(活动上下文){ this.context=上下文; fileCache=新的fileCache(上下文); executorService=Executors.newFixedThreadPool(3); } public void displayImageResource(int-resourceId,ImageViewProgress-imageView){ setImageResource(resourceId); imageView.showImage(true); } public void displayImageUri(Uri Uri,ImageViewProgress imageView){ if(uri==null){ imageView.setImageResource(R.drawable.ic_人); imageView.showImage(true); 返回; } setImageUri(uri); imageView.showImage(true); } public void displayImage(字符串url,ImageViewProgress imageView){ if(url==null | | url.length()==0){ log(“ImageLoader”,“url长度为零”); 如果(imageView!=null){ imageView.showImage(false); } 返回; } put(imageView,url); 位图位图=memoryCache.get(url); if(位图!=null){ 设置图像位图(位图); }否则{ if(sparseArrayInt.get(url.hashCode())!=0){ 位图b=sparseArrayBitmap.get(sparseArrayInt.get(url .hashCode()); 如果(b!=null){ 设置图像位图(b); 返回; } } 队列照片(url、imageView); setImageResource(默认图像); imageView.showImage(false); } } 私有void队列照片(字符串url,ImageViewProgress imageView){ PhotoToLoad p=新的PhotoToLoad(url,imageView); executorService.submit(新的PhotoLoader(p)); } //队列的任务 私有类光电负载{ 公共字符串url; 公共图像视图进度图像视图; 公共PhotoToLoad(字符串u,ImageViewProgress i){ url=u; imageView=i; } } 类photoloader实现可运行{ 光电负载光电负载; PhotoLoader(PhotoToLoad PhotoToLoad){ this.photoToLoad=photoToLoad; } @凌驾 公开募捐{ 如果(waitIfPaused()) 返回; 试一试{ if(图像视图重用(光电加载)) 返回; 位图bmp=getBitmap(photoLoad.url); if(图像视图重用(光电加载)) 返回; BitmapDisplayer bd=新的BitmapDisplayer(bmp,photoToLoad); 邮政署署长(屋宇署); }捕获(可丢弃){ th.printStackTrace(); } } } 私有布尔waitIfPaused(){ 原子布尔暂停=GetPause(); if(pause.get()){ 已同步(getPauseLock()){ if(pause.get()){ 试一试{ getPauseLock().wait(); }捕捉(中断异常e){ 返回true; } } } } 返回false; } 公共位图getBitmap(字符串url){ 文件f=FileCache.getFile(url);