I am developing an Android app which should display a list of video thumbnails in RecyclerView. A new activity will then play the video for selected thumbnail.
How do I set com.vimeo.networking.model.Picture to Android ImageView?
My code:
mVimeoClient.fetchNetworkContent(VIDEO_URI, new ModelCallback<VideoList>(VideoList.class) {
#Override
public void success(VideoList videoList) {
ArrayList<Video> videoArrayList = videoList.data;
Video video = videoArrayList.get(0);
ArrayList<com.vimeo.networking.model.Picture> arrayListPics = video.pictures.sizes;
// imageView.setImageDrawable((Drawable) pictureAL.get(0));
imageView.setImageBitmap( (Bitmap) arrayListPics.get(0));
}
#Override
public void failure(VimeoError error) {
}
});
}
The setImageBitmap() And setImageDrawable() throws
java.lang.ClassCastException
The Picture object (the one returned from arrayListPics.get(0)) in the vimeo-networking library isn't a Bitmap and therefore can't be cast to one. The Picture object has a field on it called mLink which can be access via Picture#getLink(). This will return a URI string which you then can set on your ImageView.
The simplest code you could use to get this working is:
// The ImageView you want to put the thumbnail in
ImageView yourImageView = <insert your ImageView here>;
// The video whose thumbnail you want
Video yourVideo = <insert your Video here>;
// The collection of `Picture` objects associated with this video.
// Each `Picture` in this "collection" is a different size
PictureCollection yourVideosPictures = yourVideo.getPictures();
// Get the first thumbnail/picture from this collection (not recommended)
Picture videoThumbnailPicture = yourVideosPictures.getPictures().get(0);
// The URI to the image of the thumbnail
String videoThumbnailUri = videoThumbnailPicture.getLink();
// Convert the String URI to an actual URI object
final Uri uri = Uri.parse(videoThumbnailUri);
yourImageView.setImageURI(uri);
I say this is the simplest because there are more things you should do when setting an image uri. One thing is you should base the Picture your grab from yourVideosPictures based on the width of your ImageView so that you're not needlessly pulling down a larger image than you need.
You should also probably not just set the image URI directly onto yourImageView, but instead you should use some image caching library (or some caching implementation).
I'd suggest looking into Picasso, Glide, or Fresco. Or just google "Image caching on Android".
Here's a solution using Glide 4.x.
First of all, import the lib on your project:
implementation 'com.github.bumptech.glide:glide:4.6.1'
Since the Pictures class contains an Uri as the others stated, you can use Glide to download the image for you effortlessly as follows.
// Get your ImageView
ImageView iv = findViewById(R.id.your_image_view);
// Get your thumbnails
ArrayList<com.vimeo.networking.model.Picture> arrayListPics = video.pictures.sizes;
// Load them using Glide
Glide.with(this) // Assuming "this" is your Activity, but you can also use any context here
.load(arrayListPics.get(0).getLink())
.into(iv);
That way it won't matter where is the thumbnail located (Network, file, resources), Glide will load it for you.
You can also apply some transformations or use placeholders by using Glide's RequestOptions class. Read more on how to use it here.
Please user Picasso library to load image in Image-view.
In gradle
implementation 'com.squareup.picasso:picasso:2.71828'
in your adapter class
mVimeoClient.fetchNetworkContent(VIDEO_URI, new ModelCallback<VideoList>(VideoList.class) {
#Override
public void success(VideoList videoList) {
ArrayList<Video> videoArrayList = videoList.data;
Video video = videoArrayList.get(0);
ArrayList<Pictures> arrayListPics = video.pictures.sizes;
Picasso.get().load(arrayListPics.get(0).getpath).into(view);
}
#Override
public void failure(VimeoError error) {
}
});
}
Related
I can load image path to imageView using Glide in this code:
GlideApp.with(context)
.load(imagePath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.transition(withCrossFade())
.into(imageView);
I do not want to load previously registered same path or bitmap from imageView.
==============UPDATE=================
I find this solution (thanks ADM):
Glide automatically performs setTag() function and when I call imageView.getTag() function, result is deriving SingleRequest which has loaded data (imagePath or bitmap).
But I can't access singleRequest model field, it is a private. How can I take singleRequest model field? Please help me.
As discussed you should tag e url with view.setTag().
Here setTag(Object object) takes object as argument . Whenever we call getTag() we need to cast it. below is the example.
view.setTag("htttp://www.imgur.3877383.jpg");
String url =(String)view.getTag();
if(url!=null){
// Use the url
}
Cause Argument is an Object so you can also add class object as tag.
view.setTag(myPozo);
MyPozo myPozo =(MyPozo)view.getTag();
if(myPozo!=null){
// Use the pozo
}
Also i am not aware with the use of this . But if you are working on List (ListView or RecyclerView etc) then you can directly access the dataset attached with the view by position.
you can't take "image path" from imageView by using Glide or any other libraries, one can set image bitmap or background in the imageView so you can get bitmap back from imageview if you want but you cannot get imagepath back from imageview.
if you wants to remember image path with you are going to apply as a bitmap in imageview you can do it via add the image path to arraylist and use it when needed
Try this code :
Glide.with(this).load(Uri.parse(resultUri)).asBitmap().into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
if (resource != null) {
myTouchView1.setImageBitmap(resource);
}
}
});
You should read:
Guide Documentation
The imagepath will be something like:
String asseturl = "file:///android_asset/demo1.jpg";
Glide.with(context).load(asserturl)....
So I want to basically get an image from Firebase storage (I have rules set to public).
This is what I have
ImageView image = (ImageView)findViewById(R.id.imageView);
Glide.with(this)
.load("https://firebasestorage.googleapis.com/v0/b/test-7c916.appspot.com/o/images.jpg?alt=media&token=b207cb11-9ad5-48e3-86ac-1dcb07ee6013")
.into(image);
And I instead of using an https link. I want to use a storage reference. But everytime I try to use a storage reference my app crashes.
Please help.
Like the .child() method.
You need to use StorageReference to load Firebase storage image.
// Reference to an image file in Cloud Storage
StorageReference storageReference = = FirebaseStorage.getInstance().getReference().child("myimage");
ImageView image = (ImageView)findViewById(R.id.imageView);
// Load the image using Glide
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(storageReference)
.into(image );
For more details You can check Using FirebaseUI to download and display images.
Put this class FirebaseImageLoader.java into your source, or write yourself.
Make a class anywhere in your app source like below.
#GlideModule
public class MyAppGlideModule extends AppGlideModule {
#Override
public void registerComponents(Context context, Glide glide, Registry registry) {
// Register FirebaseImageLoader to handle StorageReference
registry.append(StorageReference.class, InputStream.class,
new FirebaseImageLoader.Factory());
}
}
Where you want to load image coad like below.
StorageReference storageReference = FirebaseStorage
.getInstance().getReference().child("myimage");
Glide.with(getApplicationContext())
.load(completeStorageRefranceToImage)
.into(imageView);
Please refer for more details.
So used pRaNaY's code like this
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("images.jpg");
ImageView image = (ImageView)findViewById(R.id.imageView);
Glide.with(this).using(new FirebaseImageLoader()).load(storageReference).into(image );
There reason I want to use a reference is because I will have names of all the images in a txt file and I will read the names of images from it and create a while loop to load all the images I need into the right place.
Just one more question, How do i know if the image is null without checking if the ImageView is null?
I am trying to load images in a recycler View using Picasso using the code
Picasso.with(context).load(songs.CoverArtAlbumPath.get(position)).into(holder.primaryImageView, new Callback() {
#Override
public void onSuccess() {
Log.v("abc","suc");
}
#Override
public void onError() {
Log.v("abc","err");
}
});
And it always ends up in onError() method. I tried to load the images using the traditional way by using BitmapFactory.decodeFile and other methods and then it was working fine.
The songs.CoverArtAlbumPath.get(position) contain strings like as "/storage/emulated/0/Android/data/com.android.providers.media/albumthumbs/1456505346363"
I also tried to load an image from the drawable folder by just changing the .load() parameters in the Picasso code and it got loaded. That means no error in the context and ImageView I am using here.
The string which I am passing in the .load() method is the string path for the Cover Art of the Album from the MediaStore.
The ImageView used here is the View in the following xml code
<ImageView
android:gravity="left"
android:id="#+id/grid_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
Please Help to tell that what is wrong and what should I do to make it work.
Thanks in advance.
you can try this:
for showing image with storage path:
String path ="/storage/emulated/0/Android/data/com.android.providers.media/albumthumbs/1456505346363.png";
Picasso.with(mContext).load("file://" + path)
//.transform(new util.CircleTransform())// optional
//.placeholder(R.drawable.default1) // optional
.error(R.drawable.default1) // optional
.into(holder.primaryImageView);
for showing image from url:
String url ="http://www.domain_name.com/image.png";
Picasso.with(mContext)
.load(url)
//.placeholder(R.drawable.default1) // optional
.error(R.drawable.default1) // optional
//.transform(new CircleTransform())// optional
.into(holder.primaryImageView);
You are doing it wrong try this
String path ="/storage/emulated/0/Android/data/com.android.providers.media/albumthumbs/1456505346363.png";
Picasso.with(context).load(new File(path)).into(holder.primaryImageView);
For more Information go to http://square.github.io/picasso/
I am using displayImage() method of UniversalImageLoader library in the adapter class, which sets images(from url) in the list items. i want if i reset adapter in my listview, images should not reload if the urls are same as previous urls.
There is two solution already posted in the issue section of Universal Image Loader.
Solution #1:
You can use custom displayer:
new FadeInBitmapDisplayer(300) {
#Override
public Bitmap display(Bitmap bitmap, ImageView imageView, LoadedFrom loadedFrom) {
if (loadedFrom != LoadedFrom.MEMORY_CACHE) {
return super.display(bitmap, imageView, loadedFrom);
} else {
imageView.setImageBitmap(bitmap);
return bitmap;
}
}
}
Solution #2:
BitmapDisplayer displayer = new FadeInBitmapDisplayer(500) {
#Override
public Bitmap display(Bitmap bitmap, ImageView imageView,
LoadedFrom loadedFrom) {
if (loadedFrom != LoadedFrom.MEMORY_CACHE) {
return super.display(bitmap, imageView, loadedFrom);
} else {
imageView.setImageBitmap(bitmap);
return bitmap;
}
}
};
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.thumbnail_no_image)
.showImageOnFail(R.drawable.thumbnail_no_image)
.displayer(displayer).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).defaultDisplayImageOptions(options)
.memoryCacheSize(2 * 1024 * 1024).build();
sLoader.init(config);
I faced the same problema and went with a solution as follows
Inside the getview method after declaring your imageview try the following line as first line
myImageView.setImageResource(R.drawable.adefaultimage);
this will first show a defaultimage in the imagview and will avoid duplication of images till imageloader loads the real one
To achieve this :
Use android Lru cache in your list adapter. First time its looking very complex but its have more benifits.
Using Lru cache your image store in cache and when it will display then check from cache if it will exist then it will not down load and it will use from stored cache memory. You can also give cache memory size for your application and clear it.
Below have some links:
Tutorials:
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
http://developer.android.com/reference/android/util/LruCache.html
Example :
http://android-er.blogspot.in/2012/07/caching-bitmaps-with-lrucache.html
http://android-er.blogspot.in/2012/07/apply-lrucache-on-gridview.html
I tried above solutions but not find usefull, Finally i solved my problem by saving images from url to device(as bitmap) then get in list view from there.
I generate a ImageView in my AndroidLauncher and need to use it in one of my screen classes, so I created an interface. How can I pass that image and use it in my screen class? Do I need to make it into a Bitmap first?
What I got right now is:
Uri selectedImage = data.getData();
selectedImagePath = getPath(selectedImage);
imageView.setImageURI(selectedImage);
and my interface:
public interface purchInterface{
public void getSelectedImage();
}
and in AndroidLauncher:
#Override
public void getSelectedImage() {
imageView.getDrawable();
}
Im in deep water here. Note that I need to be able to draw this Image in my screen class.
You need to return the image encoded in some format from getSelectedImage method. Otherwise your implementation is retrieving the drawable and dropping it immediately.
You should refer to Converting Android Bitmap to LibGdx's Texture
So your interface could be
public interface purchInterface {
public byte[] getSelectedImage();
}
And implementation could be
#Override
public byte[] getSelectedImage() {
// Convert image into bitmap, encode in a byte array.
}
You can call the interface's method and decode the byte array using method described in above question.
Hope this helps.
Good luck.
Use singleton class and store image in it using setter() and later u can use getter ().
Or you convert the image to string using base64 encoding and save it shared preferences or file or database or external storage or pass as intent data to next activity and then decode it to bitmap