i am New On Android I want set image in Background Which is getting from Url ..I am using ImageLoader Class
please Help me Set Image view In Background..
This Is MY Image Loader Class
public class ImageLoader {
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
private File cacheDir;
static ArrayList<String> img_path = new ArrayList<String>();
static String sd_card_folder_name = "ImageLoader";
static int width;
public ImageLoader(Context context, Activity acc) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
DisplayMetrics displaymetrics = new DisplayMetrics();
acc.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
width = displaymetrics.widthPixels;
Log.d("width", "width = " + width);
cache.clear();
img_path = new ArrayList<String>();
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(android.os.Environment
.getExternalStorageDirectory(), sd_card_folder_name);
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
final int stub_id = R.drawable.loader;
public void DisplayImage(String url, Activity activity, ImageView imageView) {
try {
String filename = String.valueOf(url.hashCode());
File[] file_array = cacheDir.listFiles();
for (int i = 0; i < file_array.length; i++) {
img_path.add(file_array[i].getName());
}
if (img_path.contains(filename)) {
imageView.setImageBitmap(BitmapFactory
.decodeFile("/mnt/sdcard/" + sd_card_folder_name + "/"
+ filename));
} else {
if (cache.containsKey(url)) {
imageView.setImageBitmap(cache.get(url));
} else {
queuePhoto(url, activity, imageView, filename);
imageView.setImageResource(stub_id);
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView, String _name) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(url, imageView, _name);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
if (url != null && !(url.equals(""))) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
/*
* // from SD cache Bitmap b = decodeFile(f); if (b != null) return
* b;
*/
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
return null;
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=300;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public String _name;
public PhotoToLoad(String u, ImageView i, String n) {
url = u;
imageView = i;
_name = n;
}
}
PhotosQueue photosQueue = new PhotosQueue();
public void stopThread() {
photoLoaderThread.interrupt();
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while (true) {
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url);
cache.put(photoToLoad.url, bmp);
Object tag = photoToLoad.imageView.getTag();
String FileName = photoToLoad._name;
if (FileName != null
&& ((String) FileName).equals(photoToLoad._name)) {
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView, FileName);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
PhotosLoader photoLoaderThread = new PhotosLoader();
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
String file_name;
public BitmapDisplayer(Bitmap b, ImageView i, String _name) {
bitmap = b;
imageView = i;
file_name = _name;
}
public void run() {
if (bitmap != null) {
load_full_image(imageView, file_name, bitmap);
} else
imageView.setImageResource(stub_id);
}
}
private Runnable mMyRunnable = new Runnable() {
#Override
public void run() {
}
};
public void load_full_image(ImageView img, String _name, Bitmap btmp) {
img_path = new ArrayList<String>();
File[] file_array = cacheDir.listFiles();
for (int i = 0; i < file_array.length; i++) {
img_path.add(file_array[i].getName());
}
if (img_path.contains(_name)) {
img.setImageBitmap(BitmapFactory
.decodeFile("/mnt/sdcard/" + sd_card_folder_name + "/"
+ _name));
} else {
img.setImageBitmap(btmp);
}
}
public void clearCache() {
// clear memory cache
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
this is my Activity Where I Get Image In imagview
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.userprofile);
Button addfrnd=(Button)findViewById(R.id.addfrnd);
ImageView image = (ImageView) findViewById(R.id.imageView1);
UserModel user = (UserModel) getIntent().getSerializableExtra("User");
UserByIdModel tempuser = (UserByIdModel) getIntent().getSerializableExtra("UserById");
String UserId=String.valueOf(tempuser.getUser_Id());
String image_url=tempuser.getUser_Image();
int loader = R.drawable.loader;
ImageLoader imgLoader = new ImageLoader(getApplicationContext(),
UserByIdProfile.this);
image.setTag(image_url);
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
imgLoader.DisplayImage(image_url, UserByIdProfile.this, image);
you have to change in load_full_image method of imageLoader class, like below
public class ImageLoader {
...
Context mContext;
...
public ImageLoader(Context context, Activity acc) {
...
mContext = context
....
}
public void load_full_image(ImageView img, String _name, Bitmap btmp) {
img_path = new ArrayList<String>();
File[] file_array = cacheDir.listFiles();
for (int i = 0; i < file_array.length; i++) {
img_path.add(file_array[i].getName());
}
if (img_path.contains(_name)) {
Drawable d = new BitmapDrawable(mContext.getResources(),BitmapFactory
.decodeFile("/mnt/sdcard/" + sd_card_folder_name + "/"
+ _name));
img.setBackground(d);
} else {
Drawable d = new BitmapDrawable(mContext.getResources(),btmp);
img.setBackground(d);
}
}
}
try this code may be it will work
You have created a instance of ImageLoader but have not Initialize ImageLoader. For this add this line of code in your constructor after imageLoader = ImageLoader.getInstance(); :
imageLoader.init(ImageLoaderConfiguration.createDefault(ctx));
You have not declared any option for your imageLoader. Modify your DisplayImageOptions code as below:
DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.image_loading) .showImageForEmptyUri(R.drawable.no_image) .showImageOnFail(R.drawable.image_failed) .cacheInMemory(true) .cacheOnDisc(true) .bitmapConfig(Bitmap.Config.RGB_565) .build();
[Use this project aims to provide a reusable instrument for asynchronous image loading, caching and displaying.][1]
Features
1)Multithread image loading (async or sync)
2)Wide customization of ImageLoader's configuration (thread executors, downloader, decoder, 3)memory and disk cache, display image options, etc.)
4)Many customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc.)
5)Image caching in memory and/or on disk (device's file system or SD card)
6)Listening loading process (including downloading progress)
*****Android 2.0+ support
[1]: https://github.com/nostra13/Android-Universal-Image-Loader
Related
I am working with an application and have about 10 Recycle view, when i move between fragments, app crash with out of memory.
I am using a lot of images in this app
I want to know how to apply bitmap recycle as it's the main reason of the exception
My recycle adapter is:
public void onBindViewHolder(MboViewHolder holder, int position) {
GameEvent gameEvent = ev.get(position);
holder.bindPhoto(holder,cnt,gameEvent.getEventImage());}
BindPhoto mwthod is:
public void bindPhoto(MboViewHolder mbo,Context cnt, String photoUrl) {
mbo.img.setTag(photoUrl);
Bitmap imgz = Tools.getPhoto(photoUrl, 0);
if (imgz != null) {
mbo.img.setImageBitmap(imgz);
Log.e("NoDwnLd","No");
} else {
Bitmap largeIcon = BitmapFactory.decodeResource(cnt.getResources(), R.drawable.ic_default);
mbo.img.setImageBitmap(largeIcon);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
My DownloadBitmap asynctask is:
public class DownloadBitmap extends AsyncTask<String, Void, Bitmap> {
private int flag=0;
private ImageView img;
private String type;
private HashMap<String, Bitmap> map= new HashMap<>();
private Context cnt;
private String url;
public DownloadBitmap(Context cnt, ImageView img, String type) {
this.cnt = cnt;
this.img=img;
this.type=type;
}
public DownloadBitmap(Context cnt, ImageView img, String type, HashMap<String, Bitmap> map) {
this.cnt = cnt;
this.img=img;
this.type=type;
this.map=map;
}
public DownloadBitmap(Context context) {
this.cnt=context;
this.flag=2;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap=null;
if (cnt!=null){
boolean check = new CheckInternetConnection(cnt).haveNetworkConnection();
if (check) {
try {
url=params[0];
if (url==null || url.equals("")) return null;
InputStream in = new java.net.URL(url).openStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = Globals.inSampleSize;
bitmap = BitmapFactory.decodeStream(in,null,options);
return bitmap;
} catch (Exception e) {
Log.e("ImageDownload", "Download failed: " + e.getMessage());
}
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null){
bitmap=Tools.resizeImage(bitmap,500,500);
//view.setImageViewBitmap(R.id.nt_img, bitmap);
if(type == "1") Tools.sendNotification(cnt, bitmap);
if(type == "2") {
if(img.getTag()!= null && img.getTag() == url){
// keep all images stored on memory for fast retrieval
// map.put(url, bitmap);
// Log.e("url", url);
// save the image inside the image holder
//img.setImageBitmap(map.get(url));
Log.e("DwnLD",img.getTag()+"");
img.setImageBitmap(bitmap);
Tools.storePhoto(img.getTag().toString(), bitmap);
}
// Log.e("ImageDownload", "bitmap in imageview");
}
if (type == null){
// map.put(url, bitmap);
// if (img!=null && map.get(url)!=null)img.setImageBitmap(map.get(url));
if (img!=null)img.setImageBitmap(bitmap);
}
if (cnt != null && flag ==2){
Tools.storePhoto(CreateEvent1Fragment.searchResult.get(0).getEventImage(),bitmap);
// Log.e("ImageDownload", "bitmap in imageview");
}
}
}
My Tools.resizeImage is:
public static Bitmap resizeImage(Bitmap bitmap,int newWidth,int newHeight){
Bitmap resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
return resized;
}
My Tools.storePhoto is:
public static void storePhoto(String url,Bitmap image){
File img = null;
File env = new File(Environment.getExternalStorageDirectory() + Globals.DIR);
if(!env.exists()) env.mkdir();
String filename = extractUrl(url);
img=new File(Environment.getExternalStorageDirectory()+Globals.DIR+filename);
if (!img.exists()) {
// Log.e("PHOTOS",img.getAbsolutePath());
try {
FileOutputStream fos = new FileOutputStream(img);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My Tools.getPhoto is:
public static Bitmap getPhoto(String url,int type){
Bitmap bmp=null;
String filename = extractUrl(url);
File ff = new File(Environment.getExternalStorageDirectory()+Globals.DIR+filename);
if(!ff.exists()){
return bmp;
}else {
if (type != 1){
bmp = Tools.decodeFile(ff);
return bmp;
}else {
bmp = BitmapFactory.decodeFile(ff.getAbsolutePath());
return bmp;
}
}
}
My Tools.decodeFile is:
public static Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE=70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE) {
scale *= 2;
}
o.inSampleSize = scale;
o.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o);
} catch (FileNotFoundException e) {}
return null;
}
I want to apply bitmap recycle... How can I do that?
try using Libs Glide
https://github.com/bumptech/glide
change
if (imgz != null) {
mbo.img.setImageBitmap(imgz);
Log.e("NoDwnLd","No");
} else {
Bitmap largeIcon = BitmapFactory.decodeResource(cnt.getResources(), R.drawable.ic_default);
mbo.img.setImageBitmap(largeIcon);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
to
if(!photoUrl.isEmpty()) {
Glide.with(this).load(photoUrl).error(R.drawable.ic_default).into(mbo.img);
Log.e("NoDwnLd","No");
} else {
Glide.with(this).load(R.drawable.ic_default).error(R.drawable.ic_default).into(mbo.img);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
I got json data with image url. Now I want to get images from that image url from json data. So, how can i get image from that image url? Any suggestion for this?
I get following image url from json.
[{....,"image":"xyz.net/abc/img/p/9/0/9/7/9097-tonytheme_product.jpg",....},{....}]
I want to display above image url on dynamically created imageview.
I have following method for dynamially created imageview.
public void addImagesToView() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.i("ArrayList In Image","" +arraylist);
for (int i = 0; i < arraylist.size(); i++) {
imageButton = new ImageView(this);
LinearLayout.LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// for setting image margin and spacing(left,top,right,bottom)
params.setMargins(60, 20, 5, 5);
imageButton.setLayoutParams(params);
horizontalOuterLayouthome.addView(imageButton);
// horizontalOuterLayouthome.setVisibility(View.INVISIBLE);
}
}
Try this..
for (int i = 0; i < arraylist.size(); i++) {
imageButton = new ImageView(this);
Bitmap bitmap = loadImage(arraylist.get(i));
imageButton.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// for setting image margin and spacing(left,top,right,bottom)
params.setMargins(60, 20, 5, 5);
imageButton.setLayoutParams(params);
horizontalOuterLayouthome.addView(imageButton);
// horizontalOuterLayouthome.setVisibility(View.INVISIBLE);
}
loadImage function
protected Bitmap loadImage(String utl2) {
// TODO Auto-generated method stub
Log.v("utl2--", utl2);
URL imageURL = null;
Bitmap bitmap = null;
try {
imageURL = new URL(utl2);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
Try this code :
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Use below code of image loader class with image adapter.....
public class ImageLoader {
int image_size = 60;
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Context m_c;
boolean mFlag = false;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(2);
m_c=context;
}
// final int stub_id = R.drawable.animation_loding;
public void DisplayImage(String url,Bitmap my_bmp, ImageView imageView, int ad_b_width, boolean b)
{
this.mFlag = b;
this.image_size = ad_b_width;
if(url!=null)
{
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
{
if(mFlag)
{
int h = bitmap.getHeight();
int w = bitmap.getWidth();
int w1 = image_size;
if(w > w1)
{
int h1 = (h*w1)/w;
System.out.println("photos size :: "+w1 +" and "+h1);
//Bitmap bit = drawShadow(bitmap, 0, 1, 1, 1);
imageView.setLayoutParams(new LinearLayout.LayoutParams(w1, h1));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
}
else
{
imageView.setLayoutParams(new LinearLayout.LayoutParams(w, h));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
}
}
else
{
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
}
}
else
{
queuePhoto(url, imageView);
imageView.setScaleType(ScaleType.CENTER);
imageView.setBackgroundResource(R.drawable.region_images);
}
}
else if (my_bmp != null)
{
Bitmap bitmap=my_bmp;
if (bitmap != null)
{
if(mFlag)
{
int h = bitmap.getHeight();
int w = bitmap.getWidth();
int w1 = image_size;
if(w > w1)
{
int h1 = (h*w1)/w;
System.out.println("photos size :: "+w1 +" and "+h1);
//Bitmap bit = drawShadow(bitmap, 0, 1, 1, 1);
imageView.setLayoutParams(new LinearLayout.LayoutParams(w1, h1));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
}
else
{
imageView.setLayoutParams(new LinearLayout.LayoutParams(w, h));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
}
}
else
{
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
}
}
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try
{
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f)
{
try
{
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
//o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = this.image_size;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Log.i("images scal ", String.valueOf(scale));
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable
{
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad)
{
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run()
{
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
{
if(mFlag)
{
int h = bitmap.getHeight();
int w = bitmap.getWidth();
int w1 = image_size;
if(w > w1)
{
int h1 = (h*w1)/w;
System.out.println("photos size :: "+w1 +" and "+h1);
photoToLoad.imageView.setLayoutParams(new LinearLayout.LayoutParams(w1, h1));
photoToLoad.imageView.setScaleType(ScaleType.FIT_XY);
photoToLoad.imageView.setImageBitmap(bitmap);
}
else
{
photoToLoad.imageView.setLayoutParams(new LinearLayout.LayoutParams(w, h));
photoToLoad.imageView.setScaleType(ScaleType.FIT_XY);
photoToLoad.imageView.setImageBitmap(bitmap);
}
bitmap = null;
}
else
{
photoToLoad.imageView.setScaleType(ScaleType.FIT_XY);
photoToLoad.imageView.setImageBitmap(bitmap);
bitmap = null;
}
}
else
{
}
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
use Universal Image Loader it is good diaplay and cache the images https://github.com/nostra13/Android-Universal-Image-Loader
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "your folder");
// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_id)//display stub image
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
ImageView image=(ImageView)vi.findViewById(R.id.imageview);
imageLoader.displayImage(imageurl, image,options);
As Rich said picasso is a good option if you are receiving the url from JSon, it loads the image in a background async task very fast and easy to implement, for example:
String imageUrl = "xyz.net/abc/img/p/9/0/9/7/9097-tonytheme_product.jpg"; // this is an example, you can get this url from json
Picasso.with(this.getActivity()).load(imageUrl).into(imageView);
And that's it.
I am using below Url Recipe but when i am frequently running application, its leads to out of memory issue(OOM), Can any one send updated ImageLoader which can load images(thumb nail) instantly and save into cache. thanks in advance.
http://codehenge.net/blog/2011/06/android-development-tutorial-asynchronous-lazy-loading-and-caching-of-listview-images/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class ImageLoader {
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
private File cacheDir;
private Context ctx;
public ImageLoader(Context context) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
ctx = context;
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
".abcde");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
final int stub_id = R.drawable.no_image;
public void DisplayImage(String url, Activity activity, ImageView imageView) {
if (cache.containsKey(url)) {
imageView.setImageBitmap(cache.get(url));
} else {
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(url, imageView);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
public Bitmap getBitmap(String urlString) {
String filename = String.valueOf(urlString.substring(urlString
.lastIndexOf("/") + 1));
File f = new File(cacheDir, filename);
try {
if (!f.exists()) {
Bitmap bitmap = null;
InputStream is = new URL(urlString).openStream();
OutputStream os = new FileOutputStream(f);
Globals.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} else {
Bitmap bitmap = decodeFile(f);
return bitmap;
}
} catch (Exception ex) {
ex.printStackTrace();
Log.e(Data.LOG, ex.getMessage(), ex);
Bitmap icon = BitmapFactory.decodeResource(ctx.getResources(),
R.drawable.no_image);
return icon;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
PhotosQueue photosQueue = new PhotosQueue();
public void stopThread() {
photoLoaderThread.interrupt();
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
#Override
public void run() {
try {
while (true) {
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url);
cache.put(photoToLoad.url, bmp);
if (photoToLoad.url == null) {
} else {
if (((String) photoToLoad.imageView.getTag())
.equals(photoToLoad.url)) {
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
PhotosLoader photoLoaderThread = new PhotosLoader();
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i) {
bitmap = b;
imageView = i;
}
public void run() {
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
public void clearCache() {
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
}
I've been working with custom listView containing 1 imageView and 3 textViews.The image is loaded from url,due to which slows down my scrolling.Any help is appreciated..
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) LayoutInflater
.from(context);
convertView = inflater.inflate(R.layout.customvenue, parent, false);
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
VenueArray.get(position).get("VenueImage"))
.getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iconImage.setImageBitmap(bitmap);
return convertView;
}
Here VenueArray is hash map array that contains all data
add this class, it will help you out, works like a charm for me
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private ProgressBar indicator;
public ImageLoader(Context context) {
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
fileCache = new FileCache(context);
}
public void DisplayImage(String url, Context activity, ImageView imageView,
ProgressBar pbar) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
this.indicator = pbar;
indicator.setVisibility(View.INVISIBLE);
// imageView.setImageBitmap(getRoundedCornerBitmap(bitmap,13));
imageView.setImageBitmap(bitmap);
} else {
this.indicator = pbar;
indicator.setVisibility(View.INVISIBLE);
queuePhoto(url, activity, imageView);
imageView.setImageBitmap(null);
}
}
private void queuePhoto(String url, Context activity, ImageView imageView) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(url, imageView);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
PhotosQueue photosQueue = new PhotosQueue();
public void stopThread() {
photoLoaderThread.interrupt();
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while (true) {
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
String tag = imageViews.get(photoToLoad.imageView);
if (tag != null && tag.equals(photoToLoad.url)) {
//System.out.println("indicator ::" + indicator);
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView, indicator);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
PhotosLoader photoLoaderThread = new PhotosLoader();
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
// private ProgressBar indicator1;
public BitmapDisplayer(Bitmap b, ImageView i, ProgressBar indicator) {
this.bitmap = b;
this.imageView = i;
// this.indicator1 = indicator;
}
public void run() {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
Use Universal Image Downloader to display the images.
It works fine for me hope will work for u...!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android - How do I do a lazy load of images in ListView
I have been trying to figure this out for a few days but I can't seem to wrap my mind around the process. My app access a number of images from a server. As of now, it is setup to load 1 image at a time and display it. When the user hits the next button, the next image is then loaded and displayed. But the loading time is a little too long. What can be done to improve the load time of the next image?
I have been playing around with threads and AsyncTask. My idea was to keep the previous and next images in memory too. When the user hits next, I do the following:
prevImage = currentImage;
currentImage = nextImage;
nextImage = getBitmapfromURL(urlPath);
And the nextImage is actually executed in the AsyncTask or Thread. My problem with this is if the user hits the next button before that thread is completed (which simply shows a blank image). So I'm not sure if that's the way to go. Is there another way to improve the load time of these images?
Here is my class for loading image from server.
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;
import com.com.app.R;
public class ImageLoader {
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
private File cacheDir;
public ImageLoader(Context context) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"LazyList");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
final int stub_id = R.drawable.no_image;
public void DisplayImage(String url, Activity activity, ImageView imageView) {
if (cache.containsKey(url))
imageView.setImageBitmap(cache.get(url));
else {
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(url, imageView);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url) {
// // I identify images by hashcode. Not a perfect solution, good for
// the
// // demo.
// String filename = String.valueOf(url.hashCode());
// File f = new File(cacheDir, filename);
//
// // from SD cache
// Bitmap b = decodeFile(f);
// if (b != null)
// return b;
// from web
try {
return new BitmapDrawable(new URL(url).openStream()).getBitmap();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
PhotosQueue photosQueue = new PhotosQueue();
public void stopThread() {
photoLoaderThread.interrupt();
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while (true) {
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url);
cache.put(photoToLoad.url, bmp);
if (photoToLoad.url == null) {
photoToLoad.url = "http://192.168.0.2/phpdemoprojects/cardsonmobile/uploads/cards/0009.png";
} else {
if (((String) photoToLoad.imageView.getTag())
.equals(photoToLoad.url)) {
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
PhotosLoader photoLoaderThread = new PhotosLoader();
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i) {
bitmap = b;
imageView = i;
}
public void run() {
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
public void clearCache() {
// clear memory cache
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
}