I have the following code to get URL from HTML file using jsoup and save in array:
Element table2 = document.select("TABLE").get(1);
for (Element td : tr.select("td")){
Element img = td.select("img").first();
if (img == null){
continue;
}
String imgRelPath = img.attr("src");
images.add("http://hostname.com"+imgRelPath);
}
}
objImages = images.toArray();
The array has:
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/clear.gif
http://hostname.com/hobbit/gifs/static/clear.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/red.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
No I need get all images from url and put into imageView one after the other. Any idea?
Thanks in advance.
EDIT:
I'm calling Picasso.with in Async Task on onPostExecute in MainActivity:
#Override
protected void onPostExecute(Void result) {
ImageView estados = (ImageView) findViewById(R.id.estados);
Picasso.with(MainActivity.this).load("http://salesianoscarmona.com/nuevo/templates/rt_modulus_j15/images/icons/icon-crank.png").into(estados);
mProgressDialog.dismiss();
}
I have the import in the header:
import com.squareup.picasso.Picasso;
there str several great libraries that download and set image to ImageView from url:
http://square.github.io/picasso
or
https://github.com/bumptech/glide
Both are great. With picasso you can easily set url to image view and it will do the job example
Picasso.with(context).load("http://hostname.com/hobbit/gifs/static/green.gif").into(imageView);
Hope this helps
Use Universal image loader for downloading images asynchronously.
http://github.com/nostra13/Android-Universal-Image-Loader
The Library itself has a sample code to download image.you may refer it..
After downloading library add library with your project and insert the below code at necessary place
String final_url="www.google.com/.....";
ImageView image;
ImageLoader imageloader = ImageLoader.getInstance();
imageloader.init(ImageLoaderConfiguration.createDefault(context));
DisplayImageOptions options; = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading(true).cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
.cacheInMemory(true)
.displayer(new FadeInBitmapDisplayer(300)).build();
imageloader.displayImage(final_url, image);
Related
I'm trying to load image stored on aws S3 into my android app using Picasso but I am getting a blank image with no errors in my logcat and nothing to me from general debugging around the relevant lines of code.
We are having private access on images so image url can't work on browser.
i need to display image into my android app using Picasso. but it doesn't work.
My code snippet below
new Picasso.Builder(getApplicationContext()).downloader(new S3Downloader(getApplicationContext(), s3Client, bucket))
.build()
.load("https://s3-ea-east-8.amazonaws.com/music/MusicApp_3.jpg")
.placeholder(R.drawable.img_placeholder)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.into(imageView);
By using above code image is displaying only very first time after installing app. next time its only showing placeholder image
I am using this library for displaying image.
The problem isn't with Picasso, it's with loading an image from a "private" url.
please suggest solutions
You need to generate a presigned Url from S3 client and you can pass that url to picasso.
That url will be public and will have an expriy date.
You can use the below set of code , which is a aynctask which will use glide to attach private images from s3 by generating presignedurl.
public class sets3imageasync extends AsyncTask<Object, Void, String> {
// The list of objects we find in the S3 bucket
static final String s3bucket=bucket_name;
Context scontext;
ImageView image;
#Override
protected String doInBackground(Object... objects) {
// Queries files in the bucket from S3.
Calendar cal = Calendar.getInstance();
Log.d(TAG, "doInBackground: in progress");
cal.setTime(new Date());
cal.add(Calendar.HOUR, +1);
Date oneHourLater = cal.getTime();
AmazonS3Client s3 = (AmazonS3Client) objects[0];
scontext= (Context) objects[1];
image=(ImageView) objects[2];
String imagekey=(String) objects[3];
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(s3bucket, imagekey)
.withMethod(HttpMethod.GET)
.withExpiration(oneHourLater);
URL url = s3.generatePresignedUrl(generatePresignedUrlRequest);
Log.e("url was", url.toString());
return url.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute: completed "+s);
Glide.with(scontext).load(s)
.apply(new RequestOptions()
.centerCrop())
.placeholder(scontext.getResources().getDrawable(R.drawable.progress_animation))
.into((image));
}
this can be called as below
new sets3imageasync().execute(s3Client,context,Image_view);
Simply use this:
Picasso.with(getApplicationContext()).load(your_url).noFade().into(imageView);
write below code to load image in Picasso.
variables:-
String file_path -->> this is your image file path
Imageview mViewHolder.img_post_photo -->> this is your imageview to load image.
Picasso.with(context)
.load(file_path)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(mViewHolder.img_post_photo, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(context)
.load(file_path)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(mViewHolder.img_post_photo);
}
});
Set dependencies in your app build.gradle file:-
compile 'com.squareup.picasso:picasso:2.5.2'
hope this code helps you.
Using an Universal Image loader i'm trying to increase the size of the image which i got from JSON url and i tried all possible methods available in valuable stackoverflow but didn't get the right solution to increase the image size so here i am posting my code and correct me by giving your suggestions.Thanks in advance
public ImageSlideAdapter(FragmentActivity activity, List<Product> products,
HomeFragment homeFragment) {
this.activity = activity;
this.homeFragment = homeFragment;
this.products = products;
options = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.ic_error) .bitmapConfig(Bitmap.Config.ARGB_8888)
.imageScaleType(ImageScaleType.EXACTLY)
.showImageForEmptyUri(R.drawable.ic_empty).cacheInMemory() .displayer(new RoundedBitmapDisplayer(20))
.cacheOnDisc().build();
imageListener = new ImageDisplayListener();
}
I am using Universal imageloader class with RoundedBitmapDisplayer options. The RoundedBitmapDisplayer takes a particular value (here 1000) whose documentation is not available. Does anyone know what the value represents ?
private DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true).resetViewBeforeLoading(true)
.displayer(new RoundedBitmapDisplayer(1000)).showImageForEmptyUri(R.drawable.ico_user)
.showImageOnFail(R.drawable.ico_user).showImageOnLoading(R.drawable.ico_user).build();
I need to load Bitmaps into ArrayList, then convert it to Bitmap[] and pass into ArrayAdapter to inflate ListView. I use UniversalImageLoader library and here is my code:
final ArrayList<Bitmap> imgArray = new ArrayList<>(); //before the method scope, as a class field
//...some code...
File cacheDir = StorageUtils.getOwnCacheDirectory(
getApplicationContext(),
"/sdcard/Android/data/random_folder_for_cache");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext()).defaultDisplayImageOptions(options)
//.discCache(new FileCounterLimitedCache(cacheDir, 100)) - I commented it 'cause FileCounterLimitedCache isn't recognized for some reason
.build();
ImageLoader.getInstance().init(config);
for (int num=0;num<4;num++) {
ImageLoader imageLoader = ImageLoader.getInstance();
final int constNum = num;
imageLoader.loadImage("http://example.com/sample.jpg", new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
imgArray.add(constNum, loadedImage);
}
});
}
But I have some issues to struggle. Firstly, it often returns error (IndexOutOfBoundsException - current index exceeds size of ArrsyList) when first run. Then after some time (about a minute) the size of ArrayList is 1 (I check it with Toast), and then when run again right at once, it's already 4 (as it needs to be). Strange. But the main thing I need that the ArrayList is first filled and then all the other actions are done (that they be delayed and I don't have errors on the first run). How to do it?
And what to do if somebody doesn't have SD card? Btw, I couldn't find the created cache folder on my SD...
You can't add the elements in the way you're trying to. If for example the 2nd image finishes loading first, your code will correctly throw an IndexOutOfBoundsException as the location you're trying to add at is beyond the current size - see the documentation
You might be better off using an array initialised to the number of elements seeing as you know it's 4 elements - e.g.
final Bitmap[] imgArray = new Bitmap[4];
Then add the elements in your onLoadingComplete() using
imgArray[constNum] = loadedImage;
You can use a SparseArray instead of an ArrayList to avoid the IndexOutOfBoundsException.
I assume this is what you are after:
final SparseArray<Bitmap> imgArray = new SparseArray<>(); //before the method scope, as a class field
int numberOfImages;
int numberOfLoadedImages;
//...some code...
File cacheDir = StorageUtils.getOwnCacheDirectory(
getApplicationContext(),
"/sdcard/Android/data/random_folder_for_cache");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext()).defaultDisplayImageOptions(options)
//.discCache(new FileCounterLimitedCache(cacheDir, 100)) - I commented it 'cause FileCounterLimitedCache isn't recognized for some reason
.build();
ImageLoader.getInstance().init(config);
numberOfImages = 4;
numberOfLoadedImages = 0;
for (int num=0;num<4;num++) {
ImageLoader imageLoader = ImageLoader.getInstance();
final int constNum = num;
imageLoader.loadImage("http://example.com/sample.jpg", new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
imgArray.put(constNum, loadedImage);
numberOfLoadedImages++;
if(numberOfImages == numberOfLoadedImages)
{
//Do all the other actions
}
}
});
}
Universal Image Loader library contains the following method:
public void displayImage(java.lang.String uri, android.widget.ImageView imageView)
Which can be passes the image url and the ImageView to display the image on it.
plus to that, if later the same ImageView passed to the method but with a different url two thing can happen:
if old image already downloaded, normally the new image will be set to the ImageView.
if old image still downloading the library will cancel the http connection that is downloading the old image. and start downloading
the new image. (can be observed in the LogCat). this behaviour happens
when using an adapter.
Method call:
ImageLoader.getInstance().displayImage("http://hydra-media.cursecdn.com/dota2.gamepedia.com/b/bd/Earthshaker.png", imageView1);
Configuration:
Caching will not work if the defaultDisplayImageOptions not specified. which tells the library where to save those image. because this library has options to load images from Assets, Drawables or Internet:
DisplayImageOptions opts = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
With this option the images will be saved in app. internal memory.
don't worry weather the device have an external memory or not.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.defaultDisplayImageOptions(opts)
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.diskCacheSize(50 * 1024 * 1024)
.diskCacheFileCount(100)
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
I created a working github repository for it. check it out.
I'm currently loading all videos on the device into a custom ListAdapter that shows the thumbnail for the Video + more. I've noticed as I add more and more videos it gets slower to initiate. This is how my List adapter looks like:
public class VideoListAdapter extends ArrayAdapter<Video> {
private ArrayList<Video> allVideos;
private HashMap<String, Bitmap> bitmapCache;
public VideoListAdapter(Context context, ArrayList<Video> videos) {
super(context, R.layout.video_list_item, videos);
this.allVideos = videos;
/* Cache the thumbnails */
setUpBitmaps();
}
private void setUpBitmaps() {
bitmapCache = new HashMap<String, Bitmap>(allVideos.size());
for(Video video : allVideos){
bitmapCache.put(video.getDATA(), ThumbnailUtils.createVideoThumbnail(video.getDATA(), Thumbnails.MICRO_KIND));
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
row = inflater.inflate(R.layout.video_list_item, null);
} else {
row = convertView;
}
Video tmpVideo = allVideos.get(position);
String TITLE = tmpVideo.getTITLE();
long vidDur = Long.valueOf(tmpVideo.getDURATION());
String DURATION = String.format(Locale.getDefault(),"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(vidDur) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(vidDur)),
TimeUnit.MILLISECONDS.toSeconds(vidDur) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(vidDur)));
String filepath = tmpVideo.getDATA();
Bitmap thumbnail = bitmapCache.get(filepath);
TextView tvTitle = (TextView) row.findViewById(R.id.tvListItemVideoTitle);
TextView tvDuration = (TextView) row.findViewById(R.id.tvListItemVideoDuration);
ImageView ivThumbnail = (ImageView) row.findViewById(R.id.ivListItemVideoThumbnail);
tvTitle.setText(TITLE);
tvDuration.setText(DURATION);
if(thumbnail != null){
ivThumbnail.setImageBitmap(thumbnail);
}
return row;
}
}
How should load the thumbnails to decrease the time it takes to load the list adapter? Currently on my device it takes 3-4 seconds before the activity showing the adapter shows, and I only have about 15 videos.
Any suggestions would be greatly appreciated.
Marcus
Instead of showing videos in listview, Get the thumbnail for your video by passing video path and show them in the ListView.. Use this code to get thumbnail. And also use lazylist to shows images properly.
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
You can use lazyloading for this,LazyLoading will make your list scroll fast.Follow this library it will help:
https://github.com/nostra13/Android-Universal-Image-Loader
Steps of using lazy loading :
1.)Download jar file from this link:
http://www.java2s.com/Code/Jar/u/Downloaduniversalimageloader161withsrcjar.htm
2.)Create Application File :
import android.app.Application;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP
}
}
3.)On your activity in whcih you want to use ,write this it onCreate():
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.iclauncher) // resource or
// drawable
.showImageForEmptyUri(R.drawable.iclauncher) // resource or
// drawable
.showImageOnFail(R.drawable.iclauncher) // resource or
// drawable
.resetViewBeforeLoading(false) // default
.delayBeforeLoading(1000).cacheInMemory(true) // default
.cacheOnDisc(true) // default
.considerExifParams(true) // default
.imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
.bitmapConfig(Bitmap.Config.ARGB_8888) // default
.displayer(new SimpleBitmapDisplayer()) // default
.handler(new Handler()) // default
.build();
imageLoader = ImageLoader.getInstance();
4.)on your adapter write this:
imageLoader.displayImage(alist.get(position).getThumbnails(),
holder.ivImage, options, null); // alist.get(position).getThumbnails() is the url of the thumbnail and holder.ivImage is the reference of the imageview where thumbnail is to be placed