The problem is that when I open my activity shows the progress bar which while loop continuously and shows the following error code below.
There is a class project if you need more code ask in a comment
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
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);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
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();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
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;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
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;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
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() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
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)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
07-11 16:33:04.248: W/System.err(2234): java.net.MalformedURLException: Protocol not found: null
07-11 16:33:04.248: W/System.err(2234): at java.net.URL.<init>(URL.java:178)
07-11 16:33:04.248: W/System.err(2234): at java.net.URL.<init>(URL.java:127)
07-11 16:33:04.248: W/System.err(2234): at com.rozajacapp.ImageLoader.getBitmap(ImageLoader.java:66)
07-11 16:33:04.248: W/System.err(2234): at com.rozajacapp.ImageLoader.access$0(ImageLoader.java:56)
07-11 16:33:04.248: W/System.err(2234): at com.rozajacapp.ImageLoader$PhotosLoader.run(ImageLoader.java:148)
07-11 16:33:04.248: W/System.err(2234): at ava.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
07-11 16:33:04.248:
I recommend you to use Google Volley librairy for HTTP request.
See the doc here : http://developer.android.com/training/volley/index.html
Some code for downloading Image :
ImageRequest ir = new ImageRequest(url, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
iv.setImageBitmap(response);
}
}, 0, 0, null, null);
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(ir);
Related
below is my imageloader code which work fine if new image are diffrent name but if new image are same name then is not change images show old image only suppose i have image name myimage is display perfectly if i add new image in url with same name and delete previous my code again show previous image not show new image due to cache what is problem in this code help me please
private ImageLoader imgLoader;
private String strUrl = "http://solutionboat.com/work_2/asset/images/rifat.jpg";
private String strUrl1 = "http://solutionboat.com/work_2/asset/images/sobin.jpg";
private String strUrl2 = "http://solutionboat.com/work_2/asset/images/samol.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView target0 = (ImageView) findViewById(R.id.target0);
ImageView target1 = (ImageView) findViewById(R.id.target1);
ImageView target2 = (ImageView) findViewById(R.id.target2);
imgLoader = new ImageLoader(this);
imgLoader.displayImage(strUrl, target0);
imgLoader.displayImage(strUrl1, target1);
imgLoader.displayImage(strUrl2, target2);
ViewFlipper flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
flipper.startFlipping();
}
}
ImageLoader class
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews =
Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.mipmap.ic_launcher;
public void displayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if(bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
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);
Bitmap b = decodeFile(f);
if(b != null)
return b;
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 (Throwable ex) {
ex.printStackTrace();
return null;
}
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
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;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
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;
}
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
#Override
public void run() {
if(imageViewReused(photoToLoad))
return;
if(bitmap != null){
photoToLoad.imageView.setImageBitmap(bitmap);
} else {
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
public void clearCahce() {
memoryCache.clear();
fileCache.clear();
}
}
Use Picasso for any image loading/caching problems.
http://square.github.io/picasso/
i have a images inside a jsonarray but like "flag": [
"http://www.simplydecoded.com/wp-content/uploads/2013/02/Telangana2.jpg"
]
but not displaying..
i am using this tutorial for parsing the data
and i sucessfully parsed all data but except images are not coming
i am using this to call images which are in side a json array actually its a url..
JSONArray json_query_flag = c.getJSONArray("flag");
and i followd remaning all fro this question..
it just extention of that not duplicate..
and i am using below for the part for the part of downloading image to bitmap
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
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);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
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();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
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;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 2;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 4;
height_tmp /= 4;
scale *= 4;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
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() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
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)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
Try this..
JSONArray json_query_flag = c.getJSONArray("flag");
for(int i=0;i<json_query_flag.length();i++)
{
Log.v("URL"+json_query_flag.getString(i));
}
EDIT
ImageLoader imageLoader=new ImageLoader(activity.this);
and set image as
imageLoader.DisplayImage(URL, imageview);
here imageview is name of that imageview and URl is that string Url
OR
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);
image_view.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
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 lazy loading (fedorvlasov/lazylist) approach to download the image from the server but my problem is that as soon as i got the image from the server i want to save that in database but some of the images only save in the database.Please let me know the proper approach for this.
if i implemented the queue does the problem solve.
public class ImageLoader {
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
// fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(0);
}
// final int stub_id=R.drawable.stub;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=null;//memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
//imageView.setImageResource(stub_id);
}
}
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);*/
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(url);
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
// if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity entity = mHttpResponse.getEntity();
if ( entity != null)
{
// String String=EntityUtils.toByteArray(entity).toString();
// String=convertResizedImage(String);
InputStream inputStream = null;
inputStream = entity.getContent();
// byte[] imgarrbyte = new byte[inputStream.available()];
//inputStream.read(imgarrbyte);
bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, bos);
String cardimage = Base64.encodeToString(bos.toByteArray(),
Base64.DEFAULT);
byte[] imgarrbyte = null;
try {
if (cardimage!= null) {
// Utils.writetoFile(, String.valueOf(position));
byte[] tempByArr = cardimage.getBytes();
imgarrbyte = Base64.decode(tempByArr,Base64.DEFAULT);
}
if (imgarrbyte != null && imgarrbyte.length > 0) {
bitmap = BitmapFactory.decodeByteArray(imgarrbyte, 0,
imgarrbyte.length);
}
}catch(OutOfMemoryError oome)
{
oome.printStackTrace();
}
}
}
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
public String convertResizedImage(String imagedata) {
try {
// Step 1 : Image decoded
byte[] imageAsBytes = new byte[imagedata.length()];
imageAsBytes = Base64.decode(imagedata.getBytes("UTF8"),
Base64.DEFAULT);
BitmapFactory.Options opts = new BitmapFactory.Options();
int IMAGE_MAX_SIZE = 240, scale = 1;
if (opts.outHeight > IMAGE_MAX_SIZE
|| opts.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math
.log(IMAGE_MAX_SIZE
/ (double) Math.max(opts.outHeight,
opts.outWidth))
/ Math.log(0.5)));
}
// Step 2 : Compress the BITMAP
opts.inSampleSize = scale;
opts.inPurgeable = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
// Decode with inSampleSize
opts.inJustDecodeBounds = false;
opts.inDither = false;
opts.inScaled = false;
// STEP 3 :
Bitmap bitMapimage = BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length, opts);
String tempstr = new String();
if (bitMapimage != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitMapimage.compress(CompressFormat.JPEG, 100, bos);
tempstr = Base64.encodeToString(bos.toByteArray(),
Base64.DEFAULT);
}
return tempstr;
} catch (Exception e) {
// TODO Auto-generated catch block
e.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;
}
}
public void getImageSize(byte[] imgarrbyte, String fileName) {
File file = new File("/mnt/sdcard/", fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(imgarrbyte);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
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);
if(imageViewReused(photoToLoad))
return;
addBitmapTodb(photoToLoad.url,bmp); //saving in database works sometimes.
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
private void addBitmapTodb(String url, Bitmap bitmap) {
if (bitmap != null) {
Log.i("Bitmap", "addBitmapTodb==========");
Dao updateimage=new Dao();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, bos);
String cardimage = Base64.encodeToString(bos.toByteArray(),
Base64.DEFAULT);
updateimage.updateimageindb(url,cardimage);
}
}
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)
photoToLoad.imageView.setImageBitmap(bitmap);
// else
// photoToLoad.imageView.setImageResource(stub_id);
}
}
}
thanks for reply again :) yes i m currently doing the same if you check function addBitmapTodb in above code.problem is here that i have used cursoradapater and calling imageloader from getview function by passing the imageurl,I have observed some isssue as like 1.if i do scrolling on listview,the same image url request is sent to imageloader for downloading the image 2.some of the images only saved in the database(maybe becouse of synchronization issue),I want to avoid such issue so i need some help on this.
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...!