Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.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
Java 如何为gridview重置适配器?_Java_Android_Gridview - Fatal编程技术网

Java 如何为gridview重置适配器?

Java 如何为gridview重置适配器?,java,android,gridview,Java,Android,Gridview,我正在开发一个android应用程序,它从服务器下载图像,并将其显示在GridView上。为此,我使用了扩展BaseAdapter的适配器,其中我使用AsyncTask获取图像并在gridview中显示ti。代码如下 public class CloudImageAdapter extends BaseAdapter { private final String TAG = "CloudImageAdapter"; private Context context; private Thumbn

我正在开发一个android应用程序,它从服务器下载图像,并将其显示在
GridView
上。为此,我使用了扩展
BaseAdapter
的适配器,其中我使用
AsyncTask
获取图像并在gridview中显示ti。代码如下

public class CloudImageAdapter extends BaseAdapter {
private final String TAG = "CloudImageAdapter";

private Context context;
private ThumbnailCache mCache;
private LayoutInflater inflater;

private ArrayList<String> images = new ArrayList<String>();
ServerInfo server = null;

public CloudImageAdapter(Context context) {
    this.context = context;

    inflater = (LayoutInflater) this.context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // Pick cache size based on memory class of device
    final ActivityManager am = (ActivityManager) this.context
            .getSystemService(Context.ACTIVITY_SERVICE);
    final int memoryClassBytes = am.getMemoryClass() * 1024 * 1024;
    mCache = new ThumbnailCache(memoryClassBytes / 2);
    server = ServerInfo.getServerInstance(context);

}

public void putImages(String imageName) {
    images.add(imageName);
}

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

@Override
public Object getItem(int posotion) {
    Log.i(TAG, "getItem() returns -> " + images.get(posotion));
    return images.get(posotion);
}

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

@Override
public View getView(int position, View converView, ViewGroup parent) {
    ImageView imageView;
    if (converView == null) {
        converView = inflater.inflate(R.layout.single_image_frame, null);
        imageView = (ImageView) converView
                .findViewById(R.id.singleImageFrame);
        imageView.setImageBitmap(null);
        imageView.setBackgroundResource(R.drawable.empty_photo);
    } else {
        imageView = (ImageView) converView;
    }
    final AsyncImageDecoder oldTask = (AsyncImageDecoder) imageView
            .getTag();
    if (oldTask != null) {
        oldTask.cancel(false);
    }

    Bitmap bitmap = mCache.get(images.get(position));
    if (bitmap == null) {
        AsyncImageDecoder task = new AsyncImageDecoder(imageView);
        task.execute(images.get(position));
        imageView.setTag(task);
    }
    imageView.setImageBitmap(bitmap);
    return converView;
}

class Holder {
    ImageView frame;
}

/**
 * Simple extension that uses {@link Bitmap} instances as keys, using their
 * memory footprint in bytes for sizing.
 */
public static class ThumbnailCache extends
        android.support.v4.util.LruCache<String, Bitmap> {
    public ThumbnailCache(int maxSizeBytes) {
        super(maxSizeBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap data) {
        return data.getByteCount();
    }
}

class AsyncImageDecoder extends AsyncTask<String, Void, Bitmap> {
    private String END = "End-Of-File";
    private final WeakReference<ImageView> imageViewReference;
    float rotation = 0;

    public AsyncImageDecoder(ImageView frame) {
        imageViewReference = new WeakReference<ImageView>(frame);
    }

    @Override
    protected Bitmap doInBackground(String... imageName) {
        Log.i(TAG, "AsyncImageDecoder::doInBackground() image -> "
                + imageName[0]);
        Bitmap bitmap;
        try {
            bitmap = downloadImage(imageName[0]);
            mCache.put(String.valueOf(imageName[0]), bitmap);
            // rotation = getCameraPhotoOrientation(imagePath);
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap image) {
        if (imageViewReference != null && image != null) {
            final ImageView imageView = (ImageView) imageViewReference
                    .get();
            if (imageView != null) {
                /*
                 * if(image.getHeight() < image.getWidth())
                 * imageView.setRotation(90);
                 */
                imageView.setImageBitmap(image);
            }
        }
    }

    private Bitmap downloadImage(String path) throws IOException {

        Bitmap thumb = null;
        Socket socket = new Socket();
        socket.connect(server.getServerAddress());
        DataOutputStream out = new DataOutputStream(
                socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject header = new JSONObject();
        JSONObject inner = new JSONObject();
        try {
            inner.put("command", "thumbnail");
            inner.put("user", server.getUser());
            inner.put("path", path);
            header.put("header", inner);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        out.write(header.toString().getBytes());
        out.write(END.getBytes());

        /*
         * Reading thumbnails from the cloud
         */
        byte[] temp = new byte[1024]; // Temporary byte array to read from
                                        // the socket
        byte[] store = null; // Reference variable to keep the byte array
        int len = 0; // Length of the array
        int receivedCount = 0;
        while (true) {
            receivedCount = input.read(temp);
            if (receivedCount <= 0) {
                thumb = decodeSampledBitmapFromUri(store, 50, 50);
                /*
                 * thumb = BitmapFactory.decodeByteArray(store, 0,
                 * store.length);
                 */
                break; // Break when there is no more data to be read
            }
            byte[] buffer = new byte[len + receivedCount];
            if (store != null) {
                System.arraycopy(store, 0, buffer, 0, store.length);
                System.arraycopy(temp, 0, buffer, len, receivedCount);
            } else {
                System.arraycopy(temp, 0, buffer, 0, receivedCount);
            }
            store = buffer;
            len = len + receivedCount;
        }
        input.close();
        out.close();
        socket.close();

        return thumb;
    }

    private Bitmap decodeSampledBitmapFromUri(byte[] data, int width,
            int height) {
        Bitmap bm = null;
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 140, 120);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        return bm;

    }

    private int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height
                        / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

}}
公共类CloudImageAdapter扩展了BaseAdapter{
私有最终字符串标记=“CloudImageAdapter”;
私人语境;
私有ThumbnailCache-mCache;
私人充气机;
私有ArrayList图像=新建ArrayList();
ServerInfo server=null;
公共CloudImageAdapter(上下文){
this.context=上下文;
充气器=(LayoutInflater)this.context
.getSystemService(上下文布局\充气机\服务);
//根据设备的内存类别选择缓存大小
最终ActivityManager am=(ActivityManager)this.context
.getSystemService(Context.ACTIVITY\u服务);
final int memoryClassBytes=am.getMemoryClass()*1024*1024;
mCache=new ThumbnailCache(memoryClassBytes/2);
server=ServerInfo.getServerInstance(上下文);
}
公共图像(字符串imageName){
images.add(imageName);
}
@凌驾
public int getCount(){
返回图像。size();
}
@凌驾
公共对象getItem(int posotion){
i(标记,“getItem()返回->”+images.get(posotion));
返回图像.get(posotion);
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(内部位置、视图对流视图、视图组父视图){
图像视图图像视图;
如果(converView==null){
converView=充气机。充气(R.layout.single_image_frame,空);
imageView=(imageView)converView
.findViewById(R.id.singleImageFrame);
setImageBitmap(空);
imageView.setBackgroundResource(R.drawable.empty_photo);
}否则{
imageView=(imageView)converView;
}
最终AsyncImageDecoder oldTask=(AsyncImageDecoder)图像视图
.getTag();
if(oldTask!=null){
oldTask.cancel(false);
}
位图Bitmap=mCache.get(images.get(position));
如果(位图==null){
AsyncImageDecoder任务=新的AsyncImageDecoder(imageView);
task.execute(images.get(position));
setTag(任务);
}
设置图像位图(位图);
返回对流视图;
}
阶级持有者{
图像视图框;
}
/**
*使用{@link Bitmap}实例作为键的简单扩展,使用它们的
*用于调整大小的内存占用(字节)。
*/
公共静态类ThumbnailCache扩展
android.support.v4.util.LruCache{
公共ThumbnailCache(int-maxSizeBytes){
超级(最大尺寸字节);
}
@凌驾
受保护的int-sizeOf(字符串键、位图数据){
返回数据。getByteCount();
}
}
类AsyncImageDecoder扩展了AsyncTask{
私有字符串END=“文件结束”;
私有最终WeakReference imageViewReference;
浮动旋转=0;
公共异步图像解码器(图像视图帧){
imageViewReference=新的WeakReference(帧);
}
@凌驾
受保护位图doInBackground(字符串…图像名称){
Log.i(标记,“AsyncImageDecoder::doInBackground()image->”
+imageName[0]);
位图;
试一试{
位图=下载图像(imageName[0]);
mCache.put(String.valueOf(imageName[0]),位图);
//旋转=getCameraPhotoOrientation(图像路径);
返回位图;
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(位图图像){
if(imageViewReference!=null&&image!=null){
最终图像视图图像视图=(图像视图)图像视图参考
.get();
如果(imageView!=null){
/*
*if(image.getHeight()要求宽度){
如果(宽度>高度){
inSampleSize=数学圆((浮动)高度
/(浮动)高度);
}否则{
inSampleSize=数学圆((浮动)宽度/(浮动)宽度);
}
}
返回样本大小;
}
}}
问题是,当我在选项卡上运行此代码时,大约有30个图像被下载。当我从活动导航到任何其他活动(没有完全加载图像)时,应用程序将等待图像下载完成。是否有任何方法停止所有
异步
if (isCancelled()) 
    break;
task.cancel(true);
class AsyncImageDecoder extends AsyncTask<String, Void, Bitmap> {
private String END = "End-Of-File";
private final WeakReference<ImageView> imageViewReference;
float rotation = 0;

boolean resume = true;
boolean pause = false;
private String WATCH_DOG = "griffin";

public AsyncImageDecoder(ImageView frame) {
    imageViewReference = new WeakReference<ImageView>(frame);
}

@Override
protected Bitmap doInBackground(String... imageName) {
    Log.i(TAG, "AsyncImageDecoder::doInBackground() image -> "
            + imageName[0]);
    Bitmap bitmap;
    while(resume){
        try {
            bitmap = downloadImage(imageName[0]);
            mCache.put(String.valueOf(imageName[0]), bitmap);
            // rotation = getCameraPhotoOrientation(imagePath);
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(pause){ //This checks if the task has been paused and sleeps it till it has been notified to wake up
            syncronized(WATCH_DOG){
                try{
                    WATCH_DOG.wait();
                } catch (InterruptedException e){e.printStackTrace();}
                pause = false;
            }
        }
    }
    return null;
}

public void pauseTask(){
    pause = true;
}

public void wakeUp(){
    synchronized(WATCH_DOG){
        WATCH_DOG.notify();
    }
}

@Override
protected void onPostExecute(Bitmap image) {
    if (imageViewReference != null && image != null) {
        final ImageView imageView = (ImageView) imageViewReference
                .get();
        if (imageView != null) {
            /*
             * if(image.getHeight() < image.getWidth())
             * imageView.setRotation(90);
             */
            imageView.setImageBitmap(image);
        }
    }
}

private Bitmap downloadImage(String path) throws IOException {

    Bitmap thumb = null;
    Socket socket = new Socket();
    socket.connect(server.getServerAddress());
    DataOutputStream out = new DataOutputStream(
            socket.getOutputStream());
    DataInputStream input = new DataInputStream(socket.getInputStream());

    JSONObject header = new JSONObject();
    JSONObject inner = new JSONObject();
    try {
        inner.put("command", "thumbnail");
        inner.put("user", server.getUser());
        inner.put("path", path);
        header.put("header", inner);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    out.write(header.toString().getBytes());
    out.write(END.getBytes());

    /*
     * Reading thumbnails from the cloud
     */
    byte[] temp = new byte[1024]; // Temporary byte array to read from
                                    // the socket
    byte[] store = null; // Reference variable to keep the byte array
    int len = 0; // Length of the array
    int receivedCount = 0;
    while (true) {
        receivedCount = input.read(temp);
        if (receivedCount <= 0) {
            thumb = decodeSampledBitmapFromUri(store, 50, 50);
            /*
             * thumb = BitmapFactory.decodeByteArray(store, 0,
             * store.length);
             */
            break; // Break when there is no more data to be read
        }
        byte[] buffer = new byte[len + receivedCount];
        if (store != null) {
            System.arraycopy(store, 0, buffer, 0, store.length);
            System.arraycopy(temp, 0, buffer, len, receivedCount);
        } else {
            System.arraycopy(temp, 0, buffer, 0, receivedCount);
        }
        store = buffer;
        len = len + receivedCount;
    }
    input.close();
    out.close();
    socket.close();

    return thumb;
}

private Bitmap decodeSampledBitmapFromUri(byte[] data, int width,
        int height) {
    Bitmap bm = null;
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, 140, 120);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeByteArray(data, 0, data.length, options);
    return bm;

}

private int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height
                    / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}

}}
@Override
public void onPause(){
    super.onPause();
    task.pauseTask();
}

@Override
public void onResume(){
    super.onResume();
    task.wakeUp();
}