Android:如果已经有缓存文件,如何避免每次从Parse获取图像?

时间:2014-09-21 10:16:10

标签: android caching gridview parse-platform

学习从Parse获取图像并填充到gridview,我按照http://www.androidbegin.com/tutorial/android-parse-com-gridview-tutorial/的示例来实现从Parse数据库加载图像的Gridview。

Public_download_preview类

public class Public_download_preview extends Activity 
{
    GridView gridview;
    int gridsize = 256 / 3;
    List<ParseObject> ob;
    ProgressDialog mProgressDialog;
    GridViewAdapter adapter;
    private List<Photos> photoarraylist = null;

    Button btn_back, btn_refresh;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview_main);
        btn_refresh = (Button) findViewById(R.id.btn_refresh);
        btn_back = (Button) findViewById(R.id.btn_back);
        new RemoteDataTask().execute();

        btn_back.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View arg0) 
            {
                onBackPressed();
            }
        }); 
        btn_refresh.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View arg0) 
            {
                Intent intent = new Intent(Public_download_preview.this, Public_download_preview.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivityForResult(intent, 0);
                overridePendingTransition(0, 0); // 0 for no animation
                Public_download_preview.this.finish();      
            }
        }); 
    }

    private class RemoteDataTask extends AsyncTask<Void, Void, Void> 
    {
        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(Public_download_preview.this);
            mProgressDialog.setTitle("Fetching Gags");
            mProgressDialog.setMessage("Please wait...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) 
        {
            // Create the array
            photoarraylist = new ArrayList<Photos>();
            try 
            {
                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("photo_database");
                query.orderByAscending("photo_id");
                ob = query.find();
                for (ParseObject photo_data : ob) 
                {
                    ParseFile image = (ParseFile) photo_data.get("photo_file");
                    Photos map = new Photos();
                    map.set_photo_ref(image.getUrl());
                    map.set_user_name((String) photo_data.get("user_name"));
                    map.set_photo_title((String) photo_data.get("photo_title"));
                    map.set_photo_content((String) photo_data.get("photo_content"));
                    map.set_photo_category((String) photo_data.get("category"));
                    map.set_photo_status((String) photo_data.get("status"));
                    photoarraylist.add(map);
                }
            } 
            catch (ParseException e) 
            {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) 
        {
            gridview = (GridView) findViewById(R.id.gridview);
            // Pass the results into ListViewAdapter.java
            adapter = new GridViewAdapter(Public_download_preview.this, photoarraylist, gridsize);
            gridview.setAdapter(adapter);
            mProgressDialog.dismiss();
        }
    }

    @Override  
    protected void onResume() 
    {  
        super.onResume();   
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int screen_width = metrics.widthPixels;
        int screen_height = metrics.heightPixels;

        if(screen_height<screen_width)
        {
            int temp = screen_height;
            screen_height = screen_width;
            screen_width = temp;
        }
        Constant.SCREEN_H = screen_height;
        Constant.SCREEN_W = screen_width;   

        gridsize = screen_width / 3;    
    }

GridViewAdapter类

public class GridViewAdapter extends BaseAdapter 
{
    Context context;
    LayoutInflater inflater;
    ImageLoader imageLoader;
    private List<Photos> photoarraylist = null;
    private ArrayList<Photos> arraylist;

    public GridViewAdapter(Context context, List<Photos> photoarraylist, int size) 
    {
        this.context = context;
        this.photoarraylist = photoarraylist;
        inflater = LayoutInflater.from(context);
        this.arraylist = new ArrayList<Photos>();
        this.arraylist.addAll(photoarraylist);
        imageLoader = new ImageLoader(context, size);
    }

    public class ViewHolder 
    {
        ImageView photo_file;
    }

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

    @Override
    public Object getItem(int position) 
    {
        return photoarraylist.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);
            holder.photo_file = (ImageView) view.findViewById(R.id.photo_file);
            view.setTag(holder);
        } 
        else 
        {
            holder = (ViewHolder) view.getTag();
        }
        imageLoader.DisplayImage(photoarraylist.get(position).get_photo_ref(), holder.photo_file);      
        view.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View arg0) 
            {
                Intent intent = new Intent(context, Public_download_detail.class);
                intent.putExtra("photo", photoarraylist.get(position).get_photo_ref());
                intent.putExtra("user_name", (photoarraylist.get(position).get_user_name()));
                intent.putExtra("photo_title", (photoarraylist.get(position).get_photo_title()));
                intent.putExtra("photo_content", (photoarraylist.get(position).get_photo_content()));
                intent.putExtra("category", (photoarraylist.get(position).get_photo_category()));
                intent.putExtra("status", (photoarraylist.get(position).get_photo_status()));
                ((Activity) context).startActivity (intent);
            }
        });
        return view;
    } 
}

及其标准ImageLoader类

public class ImageLoader 
{
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    int sizee =100;
    private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    Handler handler = new Handler();

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

    final int stub_id = R.drawable.temp_img;

    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, int size) 
    {
        File f = fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f, size);
        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, size);
            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, int size) 
    {
        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. 
            // Required size means the min requried dimension
            final int REQUIRED_SIZE = size;
            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, sizee);
                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();
    }

问题:

每次返回public_download_preview类时,都会执行RemoteDataTask而不考虑是否存在缓存文件。我想以一种方式实现,如果有缓存文件,那么就没有必要获取在线图像。如果那么如何在代码中进行修改?

非常感谢您的建议!

1 个答案:

答案 0 :(得分:0)

使用Universal ImageLoader库或Picasso

UniversalImageLoader

Piccaso 它可以缓存图像

并加快图片加载