Load image from url, using cycle
-
14-11-2019 - |
Question
I'm using this code for downloading image from server:
public Bitmap getBitmap(String path){
URL url=new URL(path);
URLConnection connection=url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap bmp=BitmapFactory.decodeStream(is);
return bmp;
}
It works fine for 1 image, but if I'm using this in cycle, on second, third etc iterations it returns something strange (Bitmap's mWidth
and mHeight
fields are -1
). Where can be the problem?
(path
on second, third etc. iterations are fine, I checked this)
EDIT
Example of cycle:
//images - is a String array
for(int i=0; i<images.length(); i++){
Bitmap bmp=getBitmap(images[i]);
}
Ss you can see, there is nothing unusual in this cycle
Solution
Try calling Bitmap.recycle
after you've finished with one Bitmap but before you load the next.
The problem is, that even than maybe won't help - Bitmaps can't resize themselves.
Maybe, better make array of bitmaps - one for ever path.
I am afraid, that java machine (or compiler) due to optimization doesn't destroy the previous bitmap, but tries to reuse it. Please, write here about results. It is interesting.
try to read the size of images not reading them:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap btemp = BitmapFactory.decodeFile(selectedImagePath,options);
after this use below code to get height and width:
options.outHeight for height
options.outWidth for width
What do you see?
Try to change the order of the paths - again only the first will be OK? If not, the problem is in files. If yes, in connection/stream/factory.