Hot questions for Using Glide in imageview

Question:

I have a lot of doubts about the treatment of the images in android, and I was hoping to see if you could solve them.

At this point I have an image that occupies 320 dp high, and match_parent width, which is around 60% of the screen. This image of the load with Glide, of some images in 1080 that I have personally.

I tried to make centroCrop and fitXY, but always deform the images. The first type I know cuts the image, but the second one fits a size, but it does deform the image high or wide.

Is there any way, to insert it with Glide and see it as it is? What properties have I to touch on ImageView and which of Glide?

<ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:nestedScrollingEnabled="false"
        app:layout_collapseMode="parallax"
        android:scaleType="fitXY"
        app:layout_scrollFlags="scroll|enterAlways" />

Answer:

Override must be accessed via RequestOptions in the most recent version of Glide 4.x. You can add RequestOptions through apply()

Glide
    .with(context)
    .load(path)
    .apply(new RequestOptions().override(600, 200))
    .into(imageViewResizeCenterCrop);

Question:

Android Studio 3.0 Beta 5
robolectric:3.3.1

I have a the following view holder that loads a image url using the glide library. I am trying to find a way to unit test this:

    public class MovieActorsViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.civActorPicture) CircleImageView actorPicture;
        @BindView(R.id.tvName) TextView name;
        @BindView(R.id.tvCharacter) TextView character;

        private Context context;

        public MovieActorsViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            context = itemView.getContext();
        }

        public void populateActor(Actor actor) {
            Glide.with(context)
                    .load(actor.getPicturePath())
                    .placeholder(R.drawable.people_placeholder)
                    .into(actorPicture);

            name.setText(actor.getName());
            character.setText(actor.getCharacter());
        }
    }

This is the unit test I have done, but I am not sure how can I unit test the image view. I am not sure using Mockito to mock the Glide library would work?

@RunWith(RobolectricTestRunner.class)
public class MovieActorsViewHolderTest {
    private MovieActorsViewHolder movieActorsViewHolder;

    @Before
    public void setup() {
        final Context context = ShadowApplication.getInstance().getApplicationContext();
        final View view = LayoutInflater.from(context).inflate(R.layout.movie_actors_item, new LinearLayout(context));

        movieActorsViewHolder = new MovieActorsViewHolder(view);
    }

    @Test
    public void testShouldPopulateActorWithValidData() {
        final Actor actor = getActor();
        movieActorsViewHolder.populateActor(actor);

        /* test that the image view */
    final ShadowDrawable shadowDrawable = Shadows.shadowOf(movieActorsViewHolder.actorPicture.getDrawable());
    final Drawable drawable = Drawable.createFromPath(actor.getPicturePath());
    assertThat(drawable, is(shadowDrawable.getCreatedFromResId()));

        assertThat(movieActorsViewHolder.name.getText(), is(actor.getName()));
        assertThat(movieActorsViewHolder.character.getText(), is(actor.getCharacter()));
    }

  private Actor getActor() {
    return new Actor(
            "https://image.tmdb.org/t/p/w92/dRLSoufWtc16F5fliK4ECIVs56p.jpg",
            "Robert Danny Junior",
            "Iron Man");
}

}

Output:

Expected: is <org.robolectric.shadows.ShadowBitmapDrawable@ffffffe0>
     but: was <android.graphics.drawable.BitmapDrawable@ffffffe0>
Expected :is <org.robolectric.shadows.ShadowBitmapDrawable@ffffffe0>

Actual   :<android.graphics.drawable.BitmapDrawable@ffffffe0>

Many thanks for any suggestions.


Answer:

but I am not sure how can I unit test the image view

I think you are on the wrong way: you want to test whether Glide is working as expected. That's not your responsibility as a client of that library. Glide has its own tests that verify it works as expected, you should only unit test the logics that you implement within your app.

Nevertheless, if you still want to do something similar, than you have to introduce some separation in your ViewHolder: a component that is responsible for loading image into ImageView.


    public interface ImageLoader {

        void load(Context context,
                  String path,
                  @DrawableRes int placeholder,
                  ImageView imageView);
    }

Whose implementation is following class:


    public class ImageLoaderImpl implements ImageLoader {

        @Override
        public void load(Context context, String path, int placeholder, ImageView imageView) {
            Glide.with(context)
                    .load(path)
                    .placeholder(placeholder)
                    .into(imageView);
        }

    }

Now your ViewHolder will become something like this:


    class MovieActorsViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.picture)
        ImageView imageView;
        // other views

        ImageLoader imageLoader;

        MovieActorsViewHolder(View itemView, ImageLoader imageLoader) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            this.imageLoader = imageLoader;
        }

        void populateActor(Actor actor) {
            imageLoader.load(itemView.getContext(),
                    actor.getPicturePath(),
                    R.drawable.people_placeholder,
                    imageView);

            // other actions                
        }

    }

This will give you flexibility to mock ImageLoader class.

Now to the test. Here's the setup:


    @Before
    public void setup() {
        imageLoader = Mockito.mock(ImageLoader.class);

        activity = Robolectric.setupActivity(MainActivity.class);
        ViewGroup root = (ViewGroup) activity.findViewById(R.id.root);

        View inflated = activity.getLayoutInflater().inflate(R.layout.item, root);
        holder = new MovieActorsViewHolder(inflated, imageLoader);
    }

And here's test method:


    @Test
    public void test() throws InterruptedException {
        final String path = "https://image.tmdb.org/t/p/w92/dRLSoufWtc16F5fliK4ECIVs56p.jpg";
        final Actor actor = new Actor(path);
        final Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class);
        final BitmapDrawable drawable = new BitmapDrawable(activity.getResources(), bitmap);

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                holder.imageView.setImageDrawable(drawable);
                return null;
            }
        }).when(imageLoader).load(activity, path, R.drawable.people_placeholder, holder.imageView);

        holder.populateActor(actor);

        assertEquals(holder.imageView.getDrawable(), drawable);
    }

This will pass. But ask yourself: what have you tested with this? Instead, a better test would be to make sure, that imageLoader.load(...) has been called with correct params, ignore logics of how Glide will download that image into ImageView.


I wasn't trying to test the Glide API, but only to test that the image was successfully loaded into the imageview, or maybe just make sure the glide was called with the correct parameters.

Those two statements are basically the same thing: if you verify that you delegate the job to Glide with correct parameters, than it verifies that Glide will load the image correctly.

Now, the question boils down to how to verify that you are delegating the job to Glide with correct parameters?

In the above mentioned scenario:


    holder.populateActor(actor);

    verify(imageLoader).load(activity, path, R.drawable.people_placeholder, holder.imageView);

This will check, whether imageLoader was queried with those parameters.

just trying to find the best way to ensure the image view has an image

What you want is to create an abstraction, that would fill in the ImageView with some mock Drawable, and within your test you would check whether the ImageView has actually been filled with that drawable. Isn't this exactly the same, that you verify that the method on your abstraction was called (in above mentioned case ImageLoader#load())? So, there is no need to explicitly check whether the ImageView was filled in with the Drawable, because it sure will, as long as you have mocked that component also.

I guess this would mean mocking the Glide

Do not depend on implementation, depend on abstraction. What if you later decide to move from Glide to SomeAwesomeImageLoder? You have to change everything within your sources as well as tests.

On the other hand, if you have a class that is responsible for image loading, you'd encapsulate the loading logics within that class only, thus only this class would need a change. Also, this gives a perfect seam to perform unit testing.

Question:

Why GlideDrawableImageViewTarget is not found in Glide4+? What is the alternative?

My code:

import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;


Glide.with(getContext())
                    .load(R.drawable.loader_gif_image)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(new GlideDrawableImageViewTarget(imageView));
        }

Answer:

UPDATE

Use below code if you are using glide:4.9.0

    Glide.with(this)
            .load("")
            .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
            .into(new DrawableImageViewTarget(imageView));


    // or use this

    Glide.with(this)
            .load("")
            .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
            .into(new CustomTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {

                }
            });

Try this

You can use new SimpleTarget<Drawable>()

    Glide.with(this)
            .load(R.drawable.ic_favorite)
            .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
            .into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
                }
            });

Try this

You can use new Target<Drawable>()

    Glide.with(this)
            .load(R.drawable.ic_favorite)
            .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
            .into(new Target<Drawable>() {
                @Override
                public void onLoadStarted(@Nullable Drawable placeholder) {

                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {

                }

                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {

                }

                @Override
                public void getSize(@NonNull SizeReadyCallback cb) {

                }

                @Override
                public void removeCallback(@NonNull SizeReadyCallback cb) {

                }

                @Override
                public void setRequest(@Nullable Request request) {

                }

                @Nullable
                @Override
                public Request getRequest() {
                    return null;
                }

                @Override
                public void onStart() {

                }

                @Override
                public void onStop() {

                }

                @Override
                public void onDestroy() {

                }
            });

Question:

I'm trying to display an image in a ImageView using Glide library, the image is in res > drawable folder, and its name retrived from a db. How can I get a resource using an Uri?, redWifi.getImagen() returns a string like "imagename.png".

I'm using the next code but doesn't show the image.

Glide.with(detallesRedGuardadaActivity.this)
                .load(Uri.parse("file:///android_asset/" + redWifi.getImagen()))
                .asBitmap()
                .into(iconoRed);

I tried with .load(Uri.parse("file://android_asset/" + redWifi.getImagen())) but still not working.


Answer:

The URL file:///android_asset/ means that you are pointing to assets folder in your project. If you don't know where to put this directory, take a look at the Project structure with Gradle here.

After that put your images in that folder, and then this should work:

Glide.with(context)
    .load(Uri.parse("file:///android_asset/"+fileName))
    .into(imageView);

Question:

I just updated Glide library from v3 to v4 in my application. But Now I am not able to load image from the url. Previously it was working fine with v3.

Here is my Glide code:

Glide.with(context).load(galleryList.get(itemPosition).getImage()).thumbnail(Glide.with(context).load(R.drawable.balls)).apply(options).into(holder.kolamImage);

What is the change in v4? I went through the document but still no help.


Answer:

If you are using Glide v4.0.0-RC1 then you need to use RequestOptions to add the placeholder, error image and other option. Here is an working example

RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .placeholder(R.mipmap.ic_launcher_round)
                    .error(R.mipmap.ic_launcher_round);



 Glide.with(this).load(image_url).apply(options).into(imageView);

Question:

I use glide to get frame from video url but glide for get frame, download the whole video and it takes time.

        RequestOptions myOptions = new RequestOptions()
            .fitCenter()
            .centerCrop().circleCrop()
            .placeholder(R.drawable.loading_circle);

       Glide.with(context)
            .asBitmap()
            .apply(myOptions)
            .load(Link)
            .into(image);

How can I get the last frame from the video?


Answer:

you can use MediaMetadataRetriever for doing that , you can also use url , code sample from here ,

.....

String url = "yoururl";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ImageView capturedImageView = (ImageView)findViewById(R.id.capturedimage);

  MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();

  mediaMetadataRetriever .setDataSource(url, new HashMap<String, String>());
  Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(1000); //unit in microsecond
  capturedImageView.setImageBitmap(bmFrame);
 }

Question:

I have an app which loads images from api into my imageView which is in my RecyclerView.

Here is my ImageView :

        <ImageView
        android:id="@+id/Group_ImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="100dp"
        android:layout_alignParentTop="true"
        android:background="@color/_Opacity"
        android:scaleType="centerInside"
        android:src="@mipmap/ic_launcher" />

and here is the image loading part in my adapter with glide :

        Glide.with(mContext).load(goodGroups.getImageUrl()).asBitmap().dontTransform().listener(new RequestListener<String, Bitmap>() {
        @Override
        public boolean onException(Exception e, String s, Target<Bitmap> target, boolean b) {
            return false;
        }

        @Override
        public boolean onResourceReady(Bitmap bitmap, String s, Target<Bitmap> target, boolean b, boolean b1) {
            bitmap.setDensity(mContext.getResources().getDisplayMetrics().densityDpi);
            return false;
        }
    }).placeholder(R.mipmap.ic_launcher).error(R.drawable.ic_menu_gallery).into(holder.imageView);

here is the screen shot of my problem below :

my problem is with the part shown by red line in the picture. the blue line shows my imageview. the red part isn't supposed to be shown. I've tried changing the ScaleType to "FitXY" or "CenterCrop" but it messes up with the picture size.I want my picture shown without any cropping, with it's original size and without these padding like spaces in ImageView.

What should I do?!


Answer:

set android:adjustViewBounds="true" for your ImageView in the code

Question:

I want display images from HTML, and I get image url source using Jsoup. But, a problem is that each post has a different number of pictures. So, I can't fix the number of ImageViews in xml layout. After I researched, I know that I can create ImageViews dynamically. So, I create ImageViews and insert them into Linearlayout. But, I can only see one picture which I inserted lastly.

package kr.ac.mju.hanmaeum.activity.notice;

import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kr.ac.mju.hanmaeum.R;
import kr.ac.mju.hanmaeum.activity.BaseActivity;
import kr.ac.mju.hanmaeum.utils.Constants;


public class NoticeContent extends BaseActivity {
    private String url, title, timestamp, content = "";
    private TextView timestampView, titleView;
    private ImageView contentImageView, contentImageView2;
    private GetImageContentTask getImageContentTask;
    private ArrayList<String> imgList;
    private LinearLayout linearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_content);

        // get intent from MainActivity.
        Intent intent = getIntent();
        url = intent.getStringExtra("URL");
        title = intent.getStringExtra("TITLE");
        timestamp = intent.getStringExtra("TIMESTAMP");

        // Set layout contents and I will change this using ButterKnife and detach them to initFunction.
        timestampView = (TextView) findViewById(R.id.contentTimestamp);
        titleView = (TextView) findViewById(R.id.contentTitle);
        contentImageView = (ImageView) findViewById(R.id.contentImage);
        contentImageView2 = (ImageView) findViewById(R.id.contentImage2);

        linearLayout = (LinearLayout) findViewById(R.id.content_Linear);
        imgList = new ArrayList<String>();

        // get title and timestamp from MainActivity.
        titleView.setText(Constants.NOTICE_TITLE + title);
        timestampView.setText(Constants.NOTICE_TIMESTAMP + timestamp);

        getImageContentTask = new GetImageContentTask();
        getImageContentTask.execute();
    }

    class GetImageContentTask extends  AsyncTask<Void, Void, ArrayList<String>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            try {
                Document doc = Jsoup.connect(url).timeout(0).get();

                Elements imgs = doc.select("#divView > img");
                for(Element img : imgs) {
                    imgList.add(img.attr("src"));
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
            return imgList;
        }

        @Override
        protected void onPostExecute(ArrayList<String> imgList) {
            super.onPostExecute(imgList);

            for(int i=0; i< imgList.size(); i++) {
                ImageView imgView = new ImageView(NoticeContent.this);
                Glide.with(NoticeContent.this).load(imgList.get(i)).override(200,200).into(imgView);
                linearLayout.addView(imgView);
            }
        }
    }
}

Answer:

You need add LayoutParams to your ImageViews, like this:

       for(int i=0; i< imgList.size(); i++) {
            ImageView imgView = new ImageView(NoticeContent.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 200);
            imgView.setLayoutParams(lp);
            Glide.with(NoticeContent.this)
                 .load(imgList.get(i))
                 .override(200,200)
                 .into(imgView);
            linearLayout.addView(imgView);
        }

Question:

In RecyclerView, I want to load images for each item using their original aspect ratio. The server don't return the size of image.

My code is as follows:

@Override
public void onBindViewHolder(K holder, int position) {
    // ....
    Glide.with(mContext)
         .load(imgUrls.get(position))
         .listener(new RequestListener<String, GlideDrawable>(){
            // ...
            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource){
                int drawableWidth = resource.getIntrinsicWidth();
                int drawableHeight = resource.getIntrinsicHeight();
                double ratio = (drawableWidth * 1.0) / (drawableHeight * 1.0);
                // depend on the ratio to set the imageView`s LayoutParams to change the imageView`s size.
                .........
                layoutParams.width = xx;
                layoutParams.height = xx;
                imageView.setLayoutParams(layoutParams);
                return false;
            }
         })
         .into(imageView);
}

But when I have scrolled the RecyclerView or refreshed the RecyclerView, the value of drawableWidth was changed, so the size of the imageView was changed that is not expected.

What is the right way to set ImageView's size in RecyclerView?


Answer:

Try this one:

    Glide.with(getContext().getApplicationContext())
                 .asBitmap()
                 .load(path)
                 .into(new SimpleTarget<Bitmap>() {
                     @Override
                     public void onResourceReady(Bitmap bitmap,
                                                 Transition<? super Bitmap> transition) {

                /*
                        requestLayout()
                        Call this when something has changed which has
                        invalidated the layout of this view.
                */
                    mImageView.requestLayout();
                    mImageView.getLayoutParams().height = newHeight;
                    mImageView.getLayoutParams().width = newWidth;


                  // Set the scale type for ImageView image scaling 
                  mImageView.setScaleType(ImageView.ScaleType.FIT_XY);

                         mImageView.setImageBitmap(bitmap);
                     }
                 });

Question:

I'm working on Recyclerview, and I want to set an image to center imageview from Recyclerview's selected item

Error : You must pass in a non null View

here I'm trying to set an image to imageview located in activity_set_back.xml from Onclick method of Recyclerview's

I have: moviesList(ArrayList) that hold all URL and I'm getting position on click only thing I need to do is set that image to img_back(Imageview) Shown in this code

MoviesAdapter.class

this is my adapter

    public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    String string_url;
    String clicked_url;
    private ArrayList<Image> moviesList;

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public ImageView img_backimage;
        public ImageView img_back;

        public MyViewHolder(View itemView) {
            super(itemView);
            img_backimage = (ImageView) itemView.findViewById(R.id.img_backimage);
            img_back =(ImageView) itemView.findViewById(R.id.img_edit_this);
            itemView.setOnClickListener(this);


        }

        @Override
        public void onClick(View view) {
            int position = getLayoutPosition(); // gets item position
            clicked_url= moviesList.get(position).getPath();
            Toast.makeText(view.getContext(),position+"",Toast.LENGTH_LONG).show();
            Glide.with(view.getContext()).load(clicked_url)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .fitCenter()
                    .crossFade()
                    .into(img_back);
        }

    }

    public MoviesAdapter(ArrayList<Image> moviesList) {
        this.moviesList = moviesList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View rootView = inflater.inflate(R.layout.image_list_row, parent, false);
        return new MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        string_url= moviesList.get(position).getPath();
        Glide.with(holder.img_backimage.getContext()).load(string_url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .fitCenter()
                .crossFade()
                .into(holder.img_backimage);
    }
    @Override
    public int getItemCount() {
        return moviesList.size();
    }
}

image_list_row.xml

<?xml version="1.0" encoding="utf-8"?>


 <RelativeLayout
        android:id="@+id/rl_single_item"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:focusable="true"
        android:orientation="horizontal"
        android:paddingBottom="8dp"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="6dp">


        <ImageView
            android:id="@+id/img_backimage"
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:layout_centerInParent="true"
            android:scaleType="fitCenter"
            android:src="@drawable/background"/>

    </RelativeLayout>

activity_set_back.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.weblogicindia.paint.SetBackActivity">

    <RelativeLayout
        android:id="@+id/rl_Paint_Area_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/grid_view_container">

        <RelativeLayout
            android:id="@+id/rl_Paint_Area2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            >

            <ImageView
                android:id="@+id/img_edit_this"
                android:layout_centerInParent="true"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                android:src="@drawable/background"/>


        </RelativeLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/grid_view_container"
        android:layout_width="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </RelativeLayout>
</RelativeLayout>

Answer:

Here your imageview- img_edit_this is inside your activity and not inside the itemview. Inorder to access the imageview in your activity from adapter, you first need to pass a listner from your activity to adapter during adapter initilalisation. Then use this listener in your adapter to change the imageview in activity.

First create an interface like this

public interface RecyclerImageClick {
void onCenterImageChange(String imagePath);
}

Make your activity implement this, for egs

public class MembersList extends AppCompatActivity implements RecyclerImageClick

Now implement the method onCenterImageChange(String imagePath) in activity

Now when initialising adapter, pass this listner into it along with arraylist like this

data= new MoviesAdapter(ArrayList<Image> moviesList,this);

Now change your adapter constructor like this

private RecyclerImageClick listener;
public MoviesAdapter(ArrayList<Image> moviesList,RecyclerImageClick listener) {
        this.moviesList = moviesList;
        this.listener=listener;
    }

Now inside the adapter's imageview click listener call listener.onCenterImageChange(imagePath)

Now inside your activity, declare your imageview and set it to the image path passed from adapter

Question:

I've got a simple use case. I have a local image uri (content://path) that I load into an ImageView - that's step 1. After a button is pressed, the image is replaced with an image from our server - that's step 2.

My code is quite simple - or at least, I can reproduce the issue even after I simplified the code to the following:

Glide.with(imageHolder.getContext()).load(url).into(imageHolder);

The first time, this is called with a local uri (content://path), followed by a remote url (http://path.com).

Loading the local uri works just fine. The problem is that, once I initiate the load from the server (which might take a second), Glide rolls back to the ImageView's background image colour. So visually I get old image -> background colour -> new image, which is quite annoying.

Is there some sort of a hidden way in Glide to work around this?


Answer:

this is because while the server image is being loaded there is a gap between removing local image and showing the new one and that gap is your problem. one of the workarounds to this issue is to give Glide a placeholder (set your local image as the placeholder) so while Glide is loading image from server it still shows the local image and once the server image is loaded the local one goes away.

Glide.with(imageHolder.getContext())
    .placeholder(YOUR_LOCAL_IMAGE_HERE)
    .load(url)
    .into(imageHolder);

Question:

Am creating a RecyclerView to show some images and text, then user can bookmark rows of RecyclerView. Images of the RecyclerView are match parent on width and height will be wrap_content. On clicking on bookmark, adapter calls notifydatasetchanged in RecyclerView. My issue is that after calling notifydatasetchanged changed, RecyclerView blinking its images by height.

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof VHITEM) {
                final VHITEM VHitem = (VHITEM) holder;
                Glide.with(mContext)
                        .load(articleDataList.get(position).SourcePath)
                        .asBitmap()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.defaultimage)
                        .error(R.drawable.defaultimage)
                        .dontAnimate()
                        .into(VHitem.imageViewTagPic); 
            }
        }

OnButton Click

    VHItem.imageViewAddRemoveBookmark.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
    notifyDataSetChanged(); }
    }

RecyclerView configuration

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);

Answer:

Try using this on RecyclerView to restrict the blinking of view.

RecyclerView.ItemAnimator animator = mRecycler.getItemAnimator();

if (animator instanceof SimpleItemAnimator) {
    ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
}

Question:

I am learning Android Glide I am creating a simple app which shows image from web to imageview using Glide but everytime it crashes when i run this app

MainActivity.java code

package com.example.cs.myglideapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {

    private ImageView img1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        img1 = findViewById(R.id.img1);

        // urls to show on imageview
        //String[] urls = {
            //"https://cdn.pixabay.com/photo/2016/03/04/01/46/bottles-1235327_960_720.jpg",
            //"https://cdn.pixabay.com/photo/2017/06/24/23/41/beer-2439237_960_720.jpg"};

        //loading image into ImageView 
        Glide.with(this)
            .load("https://cdn.pixabay.com/photo/2016/03/04/01/46/bottles-1235327_960_720.jpg")
            .into(img1);
    }
}

Answer:

You forgot to add setContentView(R.layout.activity_main);

package com.example.cs.myglideapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {

    private ImageView img1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // Add this line

        img1 = findViewById(R.id.img1);

        //loading image into ImageView 
       Glide.with(this).load("https://cdn.pixabay.com/photo/2016/03/04/01/46/bottles-1235327_960_720.jpg").into(img1);

    }
}

Question:

i use glide method.

Glide.with(this._activity).load((String) this._filePaths.get(position)).
                apply(new RequestOptions().
                        override(dimen, dimen).
                        centerCrop().
                        diskCacheStrategy(DiskCacheStrategy.ALL).
                        into(imageView);

i get error Cannot resolve method 'into(android.widget.ImageView)'.


Answer:

You're missing one ")" after the DiskCacheStrategy.ALL):

Glide.with(this._activity).load((String) this._filePaths.get(position)).
            apply(new RequestOptions().
                    override(dimen, dimen).
                    centerCrop().
                    diskCacheStrategy(DiskCacheStrategy.ALL)).
                    into(imageView);

Question:

I want to load the url into ImageView and that url is dynamic, so I created the custom Imageview class like this

public class CustomLocalCurrencyImageViewWhiteColor extends AppCompatImageView {
public CustomLocalCurrencyImageViewWhiteColor(Context context) {
    super(context);
    Glide.with(context).load(SessionManager.getCountryWiseDataObject(context).getCurrencyImageWhite()).into(this);
}

public CustomLocalCurrencyImageViewWhiteColor(Context context, AttributeSet attrs) {
    super(context, attrs);
    Glide.with(context).load(SessionManager.getCountryWiseDataObject(context).getCurrencyImageWhite()).into(this);
}

public CustomLocalCurrencyImageViewWhiteColor(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    Glide.with(context).load(SessionManager.getCountryWiseDataObject(context).getCurrencyImageWhite()).into(this);
}

}

.Its working fine when I used it the following way

 <com.kiran.example.ebitcoin.customview.CustomLocalCurrencyImageViewWhiteColor
        android:id="@+id/img"
        android:layout_width="@dimen/imageSizeTooSmallBTCLogo"
        android:layout_height="@dimen/imageSizeTooSmallBTCLogo"
        android:layout_gravity="center_vertical" />

Now, I want to change the image resource of this custom image too, dynamically, So I tried

 CustomLocalCurrencyImageViewWhiteColor img = findViewById(R.id.img);
    img.setImageResource(R.drawable.ic_bitcoin_24_white);

But unfortunately, nothing is changed. How to change the image of custom image view class dynamically?? Any one found answer of this?


Answer:

Finally , I got answer of my own question. I follow this, and done the code by following way.

public class CustomLocalCurrencyImageViewWhiteColor extends AppCompatImageView {
Context context;
public CustomLocalCurrencyImageViewWhiteColor(Context context) {
    super(context);
    Glide.with(context).load(SessionManager.getCountryWiseDataObject(context).getCurrencyImageWhite()).into(this);
}

public CustomLocalCurrencyImageViewWhiteColor(Context context, AttributeSet attrs) {
    super(context, attrs);
    Glide.with(context).load(SessionManager.getCountryWiseDataObject(context).getCurrencyImageWhite()).into(this);
}

public CustomLocalCurrencyImageViewWhiteColor(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    Glide.with(context).load(SessionManager.getCountryWiseDataObject(context).getCurrencyImageWhite()).into(this);
}

public void setImageWithGlide(Context context, Integer resId) {
    this.context = context;
    Glide.with(context).load("").placeholder(resId).into(this);
}

}

To change the image dynamically,

CustomLocalCurrencyImageViewWhiteColor img = findViewById(R.id.img);
    img.setImageWithGlide(this, R.drawable.image);

Question:

I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.

public class BookstorePreviewActivity extends AppCompatActivity {
    ImageView imageView;
    LinearLayout mShare;
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_bookstore_preview);
        imageView  = findViewById(R.id.image_preview_books);
        mShare= findViewById(R.id.download_books);
        mShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// fetching image view item from cache
                imageView.setDrawingCacheEnabled(true);
                Bitmap bitmap = imageView.getDrawingCache();
                File root = Environment.getExternalStorageDirectory();
                File cachePath = new File(root.getAbsolutePath());
                try {
                    cachePath.createNewFile();
                    FileOutputStream outputStream = new FileOutputStream(cachePath);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
// sharing image to other applications (image not found)
                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("image/*");
                share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
                startActivity(Intent.createChooser(share, "Share via"));
            }
        });

Answer:

Just Pass activity context to the takeScreenShot activity it will work!!!

public static Bitmap takeScreenShot(Activity activity) {
            View view = activity.getWindow().getDecorView();
            view.setDrawingCacheEnabled(true);
            view.buildDrawingCache();
            Bitmap b1 = view.getDrawingCache();
            Rect frame = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;

            //Find the screen dimensions to create bitmap in the same size.
            DisplayMetrics dm = activity.getResources().getDisplayMetrics();
            int width = dm.widthPixels;
            int height = dm.heightPixels;


            Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
            view.destroyDrawingCache();
            takeScreen(b,activity);
            return b;
        }

        public static void takeScreen(Bitmap bitmap,Activity a) {
            //Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
            String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
            File imageFile = new File(mPath);

            try {
                OutputStream fout = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                fout.flush();
                fout.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            openScreenshot(imageFile,a);


        }
        private static void openScreenshot(File imageFile,Activity activity) {
            Intent intent = new Intent(activity,ImageDrawActivity.class);
            intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
        }

Question:

I have a problem with Glide when i try to load in a ImageView parallax.

My picture is 1920x1080 (example: http://www.buildingagamingpcsite.com/wp-content/uploads/2016/07/Crysis3_Screenshot_TheHunter.jpg) and i try to load in a Image View with height in dp:

 <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="320dp"
            android:nestedScrollingEnabled="false"
            app:layout_collapseMode="parallax"
            app:layout_scrollFlags="scroll|enterAlways" />

I want the image take all container, but the result is that: ImageView

What is the code of glide to take this?

My code is inside a collapsingToolbarLayout:

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <!-- Collapser -->
    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapser"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <!-- Image del detalle -->
        <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="320dp"
            android:nestedScrollingEnabled="false"
            app:layout_collapseMode="parallax"
            app:layout_scrollFlags="scroll|enterAlways" />


    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

Answer:

You should add the android:scaleType attribute to your ImageView.

If you want to display the pictures in proportion, you can use centerCrop.

If you don't want to display the pictures in proportion, you can use fitXY.

You can use this.

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <!-- Collapser -->
    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapser"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <!-- Image del detalle -->
        <ImageView
            android:id="@+id/image"
            android:src="@mipmap/bg_user"
            android:layout_width="match_parent"
            android:layout_height="320dp"
            android:nestedScrollingEnabled="false"
            android:scaleType="fitXY"
            app:layout_collapseMode="parallax"
            app:layout_scrollFlags="scroll|enterAlways"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>