Hot questions for Using Glide in android viewpager

Top 10 Java Open Source / Glide / android viewpager

Question:

I have a GridView populated with images. When I click on a GridView item it should open a new Activity and show an image in full screen, but it doesn't happen.

I'm using the Glide library. I've tried to debug, but I didn't find the problem.

Any ideas?

Gallery.java

  gridViewGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                Intent intent = new Intent(AdvertisementGallery.this,FullScreenImage.class);
                intent.putExtra("image",i);

                startActivity(intent);

            }
        });

FullScreenImage.java

 viewPager.clearFocus();


        imageItems = Constants.items;


        bitmap = getIntent().getExtras().getInt("image");


        //   ImagePageAdapter imagePageAdapter = new ImagePageAdapter(this,imageItems);
        imagePageAdapter = new ImageAdapter(this,imageItems);
        viewPager.setAdapter(imagePageAdapter);

        viewPager.setCurrentItem(bitmap,false);

class ImageAdapter extends PagerAdapter {

    public Context context;
    public ArrayList data = new ArrayList();

    public ImageAdapter(Context context, ArrayList data){

        this.context = context;
        this.data = data;

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

    }

    @Override
    public int getItemPosition(Object object) {
        int position = data.indexOf(object);
        return  POSITION_NONE ;

    }

    @Override
    public boolean isViewFromObject(View view, Object object)
    {
        return view == ((LinearLayout) object);

    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View row = null;


        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.image_pager_item_list_layout, container, false);

            //  holder.imageTitle = (TextView) row.findViewById(R.id.text);
            image = (TouchImageView) row.findViewById(R.id.imgDisplay);
            row.setTag(image);
        } else {
            image = (ImageView) row.getTag();
        }

        ImageItem item = (ImageItem) data.get(position);

       Glide.with(getApplicationContext())
                .load(item.getImage())
               .into(image);

        container.addView(row);

        return row;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((LinearLayout) object);


    }
}

Answer:

First of all, you are passing the position of the image. you need to pass the item. instead of position. you need to do following changes in the following way.

in Gallery.java

 gridViewGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            ImageItem item = (ImageItem) data.get(position)

            Intent intent = new Intent(AdvertisementGallery.this,FullScreenImage.class);
            //intent.putExtra("image",i);
            intent.putExtra("imagePosition",i);

            startActivity(intent);

        }
    });

Now, Retrieve your image in FullScreenImage.java by following way.

imageItems = Constants.items;

int position=getIntent().getExtras().getInt("imagePosition");
ImageItem item = imageItems.get(position);
bitmap = item.getImage();

To set in your ViewPager you can follow this code:

imagePageAdapter = new ImageAdapter(this,imageItems);
viewPager.setAdapter(imagePageAdapter);
viewPager.setCurrentItem(position, true);

And for the issue of

some time image display and some time is not display in viewpager.

Try to add following line .placeholder (new ColorDrawable (Color.WHITE)). so the code looks like :

Glide.with(getApplicationContext())
            .load(item.getImage())
            .placeholder (new ColorDrawable (Color.WHITE))
           .into(image);

And, If you are getting issue only in release mode apk then try this solution

Question:

I am showing images with glide into viewpager. If user like the picture than he save it on button click .

   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_full_image, container, false);
    viewPager = (ImageViewPager) v.findViewById(R.id.viewpager);

    images = (ArrayList<Photos>) getArguments().getSerializable("url");
    selectedPosition = getArguments().getInt("position");
    final Button save_img = (Button) v.findViewById(R.id.save_img);
    final View view2 = viewPager.findViewWithTag("myview" + 
                                    viewPager.getCurrentItem());

    save_img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                       saveImage();
        }
    });


    myViewPagerAdapter = new MyViewPagerAdapter();
    viewPager.setAdapter(myViewPagerAdapter);
    viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

    setCurrentItem(selectedPosition);

    return v;
}

This is instantiateItem method -

 @Override
    public Object instantiateItem( final ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
        final ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
        imageViewPreview.setOnTouchListener(new ImageMatrixTouchHandler(view.getContext()));
        Photos image = images.get(position);

        final String img_title = image.getTitle();
        final String img_weight = image.getWeight();

        Glide.with(imageViewPreview.getContext())
                .load(image.getUrl())
                .asBitmap()
                .fitCenter().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                imageViewPreview.setImageBitmap(resource);

            }

        });
        view.setTag("myview" + position);

        container.addView(view);
        return view;

    }

now how can i get image resource from glide when user click on button ? I have a save image method that save bitmap in gallery.


Answer:

// inside instantiateItem make tag for image using position

Glide.with(context).load(images.get(position))
        .crossFade()
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .into(myImage);
       container.addView(view);
    yourimageview.setTag(position);

//in activity define this varaibles

final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;

//in activity use this method to save images

public void SaveImage() 
{
        final Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        final String fname = "image" + n + ".png";
        myDir.mkdirs();
        File image = new File(myDir, fname);
        ImageView Imgv = (ImageView) yourviewpager.findViewWithTag(mPager.getCurrentItem());
        Imgv.setDrawingCacheEnabled(true);
        Bitmap bitmap = Imgv.getDrawingCache();
        // Encode the file as a PNG image.
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(image);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    /* 100 to keep full quality of the image */
            outStream.flush();
            outStream.close();
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (success) {
            Toast.makeText(getApplicationContext(), R.string.savedimage, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), R.string.errorloadingimage, Toast.LENGTH_LONG).show();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            final Uri contentUri = Uri.fromFile(image);
            scanIntent.setData(contentUri);
            sendBroadcast(scanIntent);
        } else {
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
        }
    }