android - set layout background from url - android

I don't think it's duplicating 'cause all the answers I've found were made several years ago. So, I load bitmap from URL and then do it this way:
currentView.setBackground(new BitmapDrawable(result));
...where "result" is Bitmap.
But "BitmapDrawable" is deprecated and it doesn't work from API 22 or 21.
Are there some other way of converting Bitmap to Drawable or loading drawable from URL instead of Bitmap?

As the documentation tells you - don't use the deprecated
new BitmapDrawable(result)
Instead use the API 18 version
new BitmapDrawable(getActivity().getResources(), result)
Assuming you're supporting API 18+, otherwise you need to handle both version depending on the runtime API.

Use Glide to load image from URL, Glide is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.
Glide takes care of making scrolling any list of images as smooth as possible and also receive, resize and display remote image.
For more information refer here
Add below dependencies in build.gradle:
dependencies {
compile 'com.github.bumptech.glide:glide:3.6.0'
compile 'com.android.support:support-v4:19.1.0'
}
Eg project https://github.com/chrisbanes/cheesesquare
Eg usage:
#Override
public void onCreate(Bundle savedInstanceState) {
...
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);
}
In the load method just pass the URL of the image and in into just pass the view, in you case currentview.
For your scenario:
Glide.with(this).load("http://goo.gl/gEgYUd").into(currentView);

Related

Use image from url as R.drawable.image in method

I just install dev-labs-bg /fullscreen-video-view from GitHub and I want to set thumbnail, but the library method use only images from drawable.
val thumbnailResId = R.drawable.video_thumbnail
fullscreenVideoView.videoUrl(videoUrl)
.thumbnail(thumbnailResId)
How I can use image from URL to load into that method.Any clue or this is not postible
It's not supported. I've checked the newest API by myself and can confirm that no method that supports Bitmap or Drawable exists. Here is the snippet from the documentation as a confirmation:
This feature supports loading only drawables from the Android project. Source: https://github.com/dev-labs-bg/fullscreen-video-view#add-thumbnail

How to load Image and other content in UI from server

Taking example of viewpager or recyclerview in android we know that they can contain images as well.What i want to know is that how we can load images from database from server and put that images in view pager or recycler view.Upto know my understanding is that i have to make a database in server and put images in it ,now during splash screen download that images and after that put that images into view.Am i going right? Basically what i want to achieve is like shopping app which shows images which changes time to time ? how i can do same ?Do i should go with Rest API to download that images from server and then put in view also do i need to make sure that every time user opens app then it download image?
You can simply fetch .jpg URL from API and then load that image in your app by using Fresco library.
Check this out: Display images with Fresco
First add Fresco to your dependencies in app/build.gradle.
dependencies {
implementation 'com.facebook.fresco:fresco:1.10.0'
}
Don't forget to add in your AndroidManifest.xml proper permission:
<uses-permission android:name="android.permission.INTERNET"/>
Initialize Fresco in class that extend Application class. You can do it in Activity, but it's better to do it just once in Application class.
Fresco.initialize(context);
Instead of ImageView use SimpleDraweeView like this:
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/sdvImage"
android:layout_width="130dp"
android:layout_height="130dp"
fresco:placeholderImage="#drawable/myPlaceholderImage" />
Then just init your SimpleDraweeView object in Activity/ViewHolder/Fragment, parse Url string to Uri like this:
Uri imageUri = Uri.parse("https://i.imgur.com/tGbaZCY.jpg");
And you can set Uri to your SimpelDraweeView object this way:
draweeView.setImageURI(imageUri);
You can use Glide or Picasso as well. Find one that suit your needs by read this post:
Picasso v/s Imageloader v/s Fresco vs Glide

displaying an image from drive in Android

I'm using Fresco library to display images in my Android app. I'd like to display some images (jpg or png) that I have set with public grants.
When I was doing quick tests, I just took any image from internet to set a URL, but when using the real ones that I need to use, I have the following url https://drive.google.com/uc?export=view&id=<>, but as it is a redirect and, once redirected, new url is not the image itself, Fresco is unable to display it.
I have tried Picasso as an alternative library, but with out any success.
I have also tried the download url for both libraries (https://drive.google.com/uc?export=download&id=<>). But no result.
Anybody knows how could it be possible to get this images? Or the only solution is to download it (using the second url) processing the object received store a bitmap of it and displaying it?
For downloading it, what should i use and how? retrofit?
Thanks in advance.
Fresco supports different network stacks. For example, you can use OkHttp with Fresco, which should follow redirects or modify the default one to allow redirects - or write your own based on them.
Guide for OkHttp: http://frescolib.org/docs/using-other-network-layers.html
Related GitHub issue: https://github.com/facebook/fresco/issues/61
I found a solution for this problem (but could be only applicable if you use Google Cloud or Google Script).
It consists on creating a doGet() service with the following code inside:
var file = DriveApp.getFileById(fileId)
return Utilities.base64Encode(file.getBlob().getBytes());
and use that base64 value in your app. With this format, Fresco can do the magic
It is not an immediate solution, and requires to do somework in other platform that is not your Android app, but it works perfectly.
Are you sure that there is no problems with your URLs?
Picasso works with direct URLs like: https://kudago.com/media/images/place/06/66/06662fda6309ce1ee9116d13bd1c66d5.jpg
Then you can download your image like:
Picasso.with(this)
.load(url)
.noFade()
.placeholder(R.drawable.placeholder_grey) //if you want to use a stub
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//here you can operate with image after it is downloaded
}
#Override
public void onError() {
}
});
Hope it will help you.

How to display animated GIF picture in Android Widget which shows on Screen?

I'm trying to display an animated GIF picture in Widget, and I have URL for the picture. I know I can use WebView in activity with webView.loadUrl("http://my_url_here.gif"), but WebView is not supported in Android Widget.
I've already had URL for the picture, and I'm finding some ways not using third party libraries.
Does anyone know how to display it in Widget?
Where is no way to show GIF animation on RemoteViews. You can use only widgets that describes in official documentation
A bit late to the party, but I will post this for future references who want to get a widget animated.
I think this is probably what you want to achieve:
https://media.giphy.com/media/Rb7FAFdrgHr51V6zjy/giphy.gif
Fundamentally, GIF files "allow images or frames to be combined, creating basic animations", any GIF is a collection of images with continuous updates/refreshes to achieve the animated effect.
Hence, even though widgets on Android are RemoteViews that only support basic Text and Image, but if you can downsample a GIF into a series of PNGs or Bitmaps, you can achieve the animation effect by creating an async background task that updates the image bitmap or src of the Widget's RemoteView.
There are great answers on SO for converting Gifs into a collection of PNGs:
Using Glide, how can I go over each frame of GifDrawable, as Bitmap?
public class GifPlayer extends AsyncTask<String, Void, List<Bitmap>> {
#Override
protected List<Bitmap> doInBackground(String... params) {
try {
// load Gif images
InputStream in = new java.net.URL(url).openStream();
//... use Glide to convert Gifs into PNGs and save it in your local file system.
List<Bitmap> gifs = ...
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(List<Bitmap> pngArray) {
while(true) {
for(Bitmap png : pngArray){
views.setImageViewBitmap(R.id.new_widget_image, png);
WidgetManager.updateAppWidget(WidgetID, views);
Thread.sleep(500); // higher lower this number depends on how fast you want to animate
}
}
Not to mention, Android Widgets have a small memory limit, so the above code works, but it will run out of memory for larger GIFs.
In general, RemoteViews.setImageViewBitmap(viewId, bitmap) should only be used for Widgets that don't update frequently.
For frequent updates of Widget such as animating a GIF, always use setImageViewResource(viewId, resId) instead (save frames of a GIF as PNG files identified by consecutive IDs such as gif_1.png, gif_2.png, gif_3.png...)
and replace the above code by:
//...
#Override
protected void onPostExecute(List<Integer> pngArray) {
while(true) {
for(int id : pngArray){
views.setImageViewResource(R.id.new_widget_image, id);
WidgetManager.updateAppWidget(WidgetID, views);
Thread.sleep(500); // higher lower this number depends on how fast you want to animate
}
}
You can use the gifView library :https://github.com/koral--/android-gif-drawable
use this is your .xml:-
<pl.droidsonroids.gif.GifImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/src_anim"
/>
where src_anim is your loader gif file
You can use a load of different image loading libraries for this, but I recommend Fresco. They have great built-in GIF support detailed on this page which looks like the following in code:
Uri uri = Uri.parse("http://my_url_here.gif");
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(uri)
.setAutoPlayAnimations(true)
. // other setters
.build();
mSimpleDraweeView.setController(controller);
update
I never really understand where this need to not use libraries stems from, but you could just manually copy across all the code classes to your app then! The code in these libraries is battle tested and will work much more reliably than most code you decide to write alone.
That being said, there's a useful gist I've used in the past that may be what you're looking for.

Picasso Caching Doesn't Appear to be working

I am using Picasso to handle image loading and caching in my Android Udacity project and I am noticing the caching is not working as I'd expect:
As you can see on the left fragment, the image has already loaded in an earlier thread. Now, with the same URL link, I am asking Picasso to place that image in the fragment on the right.
Here is the code which generates the grid view on the left fragment (and occurs first):
https://github.com/esend7881/udacity-android-popmovie/blob/a9a1b9a19a37594bb5edd736b7ec59229fb5905a/app/src/main/java/com/ericsender/android_nanodegree/popmovie/adapters/GridViewAdapter.java#L71
String load = String.format(sImgUrl, sImgSize, movie.poster_path);
Picasso.with(mContext.getApplicationContext())
.load(load)
.placeholder(R.drawable.abc_btn_rating_star_on_mtrl_alpha)
.error(R.drawable.abc_btn_rating_star_off_mtrl_alpha)
.resize(550, 775)
.into(viewHolder.imageView);
And then here is the code which runs in the right fragment:
https://github.com/esend7881/udacity-android-popmovie/blob/a9a1b9a19a37594bb5edd736b7ec59229fb5905a/app/src/main/java/com/ericsender/android_nanodegree/popmovie/fragments/MovieDetailsFragment.java#L308
Picasso.with(getActivity().getApplicationContext())
.load(String.format(sImgUrl, sImgSize, mMovieObj.poster_path))
.error(R.drawable.blank)
.fit()// .resize(366, 516)
.into(mMovieThumb, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
Utils.log(sw.toString());
Utils.hideViewSafe(mMovieThumbProgress);
}
#Override
public void onError() {
Utils.log(sw.toString());
Utils.hideViewSafe(mMovieThumbProgress);
}
});
I am using the same application context in each as well as the load text:
String.format(sImgUrl, sImgSize, mMovieObj.poster_path))
and
getActivity().getApplicationContext()
So, I would think Picasso ought to detect when the exact same URL load link appears in the same context within a short period of time from each other and Picasso would then load the exact same image back into the app.
If this is not how Picasso caching works, then how does it?
As a comment mentioned, I'd guess this is affected by the size of the image being different in both fragments.
I'd recommend using https://github.com/facebook/fresco instead of picasso. It's more efficient, especially with different sizes. You can also directly access cached files if required https://github.com/facebook/fresco/issues/80
It's probably related to the HTTP headers received when getting the image that do not allow caching, as Picasso relies on an HTTP component to do the caching.
Try uploading your image on imgur, try hardcoding that path and see if it works. If that's the case, you'll have to find a workaround on how to get the image from the movie database.

Categories

Resources