Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.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:如果已经有缓存文件,如何避免每次从解析中获取图像?_Android_Caching_Gridview_Parse Platform - Fatal编程技术网

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

Android:如果已经有缓存文件,如何避免每次从解析中获取图像?,android,caching,gridview,parse-platform,Android,Caching,Gridview,Parse Platform,在学习如何从Parse获取图像并填充到gridview时,我将按照的示例实现gridview从Parse数据库加载图像 公共下载预览类 GridViewAdapter类 以及它的标准ImageLoader类 问题: 每次返回到public_download_preview类时,都会执行RemoteDataTask,而不考虑是否存在缓存文件。我想实现的方式是,如果有缓存文件,那么就没有必要获取在线图像。如果这样,如何在代码中修改 非常感谢你的建议 使用通用ImageLoader库或毕加索 哪一个

在学习如何从Parse获取图像并填充到gridview时,我将按照的示例实现gridview从Parse数据库加载图像

公共下载预览类 GridViewAdapter类 以及它的标准ImageLoader类 问题: 每次返回到public_download_preview类时,都会执行RemoteDataTask,而不考虑是否存在缓存文件。我想实现的方式是,如果有缓存文件,那么就没有必要获取在线图像。如果这样,如何在代码中修改


非常感谢你的建议

使用通用ImageLoader库或毕加索

哪一个可以缓存图像


并且使图像加载更快

感谢我现在已经实现了Piccaso。但是新的RemoteDataTask.execute应该如何执行;在公共场合下载预览可以写吗?如果缓存可用,则加载缓存,或者从parse下载?不知道缓存,但您可以查看universal image loader的源代码缓存是如何完成的,这对您的方向有很大帮助。我终于改用了UniversalImageLoader,因为它的实现更加简单,但比Piccaso更具定制性。
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;    
    }
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;
    } 
}
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();
    }