why cannot load multiple image into list view? - android

I am downloading the image from website and attach into listview.
URL aURL;
try {
aURL = new URL(//"http://www.orientaldaily.com.my/"+
imagepath[i]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
imageview = (ImageView) findViewById(R.id.image_alllatestnewstitle);
imageview.setVisibility(View.VISIBLE);
imageview.setScaleType(ScaleType.CENTER_CROP);
imageview.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
When i downloading only 1 image, it got no problem, however when i downloading multiple or more than 5 images and load into listview, it cause problem.
The problem was
bitmap size exceeds VM budget
How to avoid this problem?
Note: this is not duplicate any question!
Thanks.

Load lot many images causes the app to run out of memory and force closes.I think this is what happening to your application.the memory issue is a complex issue android while developing an application.this can be solved by manually clearing the unused bitmaps and by using the garbage collector.
Try using System.gc();
Try recycling the bitmap using
Bitmap.recycle();
Make all the unused bitmap null.
Deallocate all the unused memory.
This all will help you a lot and also go through this link.Use memory analyzer it will help you spot out the Deallocated memory>try this link
public void deAllocateAllMemory()
{
try
{
mGallery.imgLoader1.disposeImages();
unbindDrawables(findViewById(R.id.magazineGrid));
mGallery=null;
back.getBackground().setCallback(null);
back.setOnClickListener(null);
store.getBackground().setCallback(null);
store.setOnClickListener(null);
quickAction.setOnActionItemClickListener(null);
settings.getBackground().setCallback(null);
settings.setOnClickListener(null);
}
catch (Exception e)
{
}
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
try {
view.getBackground().setCallback(null);
((BitmapDrawable) view.getBackground()).getBitmap().recycle();
view.destroyDrawingCache();
view.notifyAll();
} catch (Exception e) {
}
}
This piece of code may help you a lil bit.

Displaying Bitmaps Efficiently tutorial could help you.

Related

I am facing java.net.MalformedURLException: no protocol: While converting url to bitmap in android

I am trying to convert url to bitmap and then set that bitmap to background as wallpaper. And all this process is getting done in background with the use of worker class in android. But I am getting no protocol error. I am fetching any one random wallpaper link from firebase then I am trying to convert it into bitmap by
try {
URL url = new URL(image_url);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
myWallpaperManager.setBitmap(image,null,false,WallpaperManager.FLAG_SYSTEM);
} catch(IOException e) {
Log.e("tag102",e.getMessage());
}
But this method gave me this error in logcat
2022-07-08 03:15:07.544 25513-25752/com.nightowl.stylo E/tag102: no protocol:
But when I put hardcoded string (showed in below method) in url method parameter then it return bitmap without any error. and wallpaper also gets changed
try {
URL url = new URL("https://images.pexels.com/photos/6336035/pexels-photo-6336035.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
myWallpaperManager.setBitmap(image,null,false,WallpaperManager.FLAG_SYSTEM);
} catch(IOException e) {
Log.e("tag102",e.getMessage());
}
But i want random string to set and get me bitmap from that. So how i can achieve that? I also try to encode url by
try {
encodedURL = URLEncoder.encode(image_url, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("tag3",e.toString());
}
I am using three kind of url in this project
https://images.pexels.com/photos/6336035/pexels-photo-6336035.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800
https://cdn.pixabay.com/photo/2020/11/27/22/07/naruto-5783102_960_720.png
https://images.unsplash.com/photo-1641414315243-196e7382c32d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1178&q=80
Any help will be appreciated.

what happen when memory is full in image gallery

there is a image gallery app which download images online. I want to know what will happen if phone memory/SD card get full; If an error will appear then what should I do?
This catches an OutofMemory error, but should check for other exceptions, too
URL aURL = null;
Bitmap bm = null;
try {
final String imageUrl = CMSServer + url;
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = new BufferedInputStream(conn.getInputStream());
is = new BufferedInputStream(conn.getInputStream());
bm = BitmapFactory.decodeStream(is, null, options);
is.close();
} catch (OutOfMemory oom) {
// do something
}
}
return bm;
}
The analogy can be made what if a class cannot adjust more students ?
So according to me :-
1. you can follow "Precaution is better than cure"
first of all you will check the sdcard itself and if its say >1MB then you will get the image.
Even if the error comes you can prompt user to delete older images to allow new images like we used to have older phones where msg memory was limited and it will ask to remove older messages to allow new messages.
Still if you get the error then perhaps i cannot exactly figure out what to do except showing the "Out of memory exception" to user.
Thanks and hope it helps.... :)
It will through IOException if no memory is left in sdcard. But if you know the size of file which you are downloading then you can check for sufficient memory and thus can avoid IOException.
Edit: Catch Exception
try
{
//your code here
}
catch(IOException ex)
{
//do stuff when exception caused.
}
if you don't know how to use/catch exception. Please google it.

Unable to clear or set blank image in imageview in android

if(bigimageS.length()==0){
show_image.setImageBitmap(null);
}else{
show_image.setImageBitmap(decodeImage(bigimageS));
}
****************
public static Bitmap decodeImage(String arrayList_image) {
BufferedInputStream bis;
URL aURL;
try{
aURL = new URL(arrayList_image);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
this is my code and i want to clear imageview.my problem is i am getting the image in bigimages String.i am adding the imageurl from w/s.in string bigimages.when i click on next btn after once image set then old image is not clear.so plz help i put condition but not working.plz help.
I am using the decodeimage for decode the image so is it any way to clear if there is no url in string..help me plz not solve yet
create a blank /transparent png image from photoshop , and apply as your image background.
You need to check the length of the url . If it is 0 then you have to set null to imageviwe.
Please try this.
if(imageneel.get(i).length() == 0)
{
show_image.setImageBitmap(null);
}
try this one code
for (int i = 0; i < imageneel.size(); i++) {
if(imageneel.get(i).trim().length() == 0){
show_image.setImageBitmap(null);
}else{
show_image.setImageBitmap(decodeImage(imageneel.get(i)));
}
}
Agree with Pranav, but i think you can also access inbuild resources of Android itself.
Try:
imgView.setImageResource(android.R.color.transparent);
finally i got the solution..i have simply set the blank like this bigimageS="";
before getdata(); method..
It is simple as passing a 0 as the resource
show_image.SetImageResource(0);

android java.lang.OutOfMemoryError: bitmap size exceeds VM budget

i've some leaks problems.
What i'm doing is loading some pictures in a table. I've created an asyncronous class for loading images.
In my table while i'm cycling the array I add my class
final LoaderImageView image = new LoaderImageView(getContext(),vgood[i].getImageUrl(),(int)(ratio *80),(int)(ratio *80));
row.addView(image);
In my asyncronous class i'm loading images from this
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), "name");
Called by
public void setImageDrawable(final String imageUrl) {
mDrawable = null;
mSpinner.setVisibility(View.VISIBLE);
mImage.setVisibility(View.GONE);
new Thread(){
public void run() {
try {
mDrawable = getDrawableFromUrl(imageUrl);
imageLoadedHandler.sendEmptyMessage(COMPLETE);
} catch (MalformedURLException e) {
imageLoadedHandler.sendEmptyMessage(FAILED);
e.printStackTrace();
} catch (IOException e) {
imageLoadedHandler.sendEmptyMessage(FAILED);
e.printStackTrace();
}
};
}.start();
}
When i've a lot of images to load the app crashes due to out of memory caused by this line
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), "name");
How can i fix that? where i'm going wrong?
thank you
Never load any tiles that you don't need. "am collecting all bitmaps from sdcard" suggests that you are decompressing every image you might ever need, which would be the wrong approach.
Use smaller tiles. 256x256 is a good size.
Load them as Config.RGB565 (i.e. 16bpp).
Regularly recycle() Bitmaps you don't need.
Basically you need to implement some sort of most-recently-used (MRU) Bitmap cache
Extrated From
Android: "java-lang-outofmemoryerror-bitmap-size-exceeds-vm-budget-android" While loading bitmaps from sdcard?

Android: Problems downloading images and converting to bitmaps

I am working on an application that downloads images from a url. The problem is that only some images are being correctly downloaded and others are not.
First off, here is the problem code:
public Bitmap downloadImage(String url) {
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(new HttpGet(url));
} catch (ClientProtocolException cpe) {
Log.i(LOG_FILE, "client protocol exception");
return null;
} catch (IOException ioe) {
Log.i(LOG_FILE, "IOE downloading image");
return null;
} catch (Exception e) {
Log.i(LOG_FILE, "Other exception downloading image");
return null;
}
// Convert images from stream to bitmap object
try {
Bitmap image = BitmapFactory.decodeStream(response.getEntity().getContent());
if(image==null)
Log.i(LOG_FILE, "image conversion failed");
return image;
} catch (Exception e) {
Log.i(LOG_FILE, "Other exception while converting image");
return null;
}
}
So what I have is a method that takes the url as a string argument and then downloads the image, converts the HttpResponse stream to a bitmap by means of the BitmapFactory.decodeStream method, and returns it. The problem is that when I am on a slow network connection (almost always 3G rather than Wi-Fi) some images are converted to null--not all of them, only some of them. Using a Wi-Fi connection works perfectly; all the images are downloaded and converted properly.
Does anyone know why this is happening? Or better, how can I fix this? How would I even go about testing to determine the problem? Any help is awesome; thank you!
This is a known issue with the JPEG decoder. There are two solutions. Either you download the entire image in a byte[] array using a ByteInputStream and then decode the array (this is what I do in code.google.com/p/shelves.) Another solution is to create a wrapper InputStream as shown below:
public class PatchInputStream extends FilterInputStream {
public PatchInputStream(InputStream in) {
super(in);
}
public long skip(long n) throws IOException {
long m = 0L;
while (m < n) {
long _m = in.skip(n-m);
if (_m == 0L) break;
m += _m;
}
return m;
}
}
Even with a WiFi connection some bitmaps (in particular .BMPs) will not be decoded. It's just a buggy decoder that can not deal with delays. If you search stackoverflow you will find some other solutions such as wrapping the HTTP stream in a buffered http entity. That works but depending on image size can take up a lot of memory. For our commerical product we ended up downloading the http stream to sdcard and then using Bitmapfactory on the dowloaded file. It's somewhat slower but 100% reliable.

Categories

Resources