Android-heap: Image in AlertDialog taking up huge heap memory and not
freeing it up
I have a particular fragment containing an image. On click of the image I
scale up the image and show it in a dialog with some title.
All this works fine.
While using DDMS I saw the heap memory shoots up by ~4Mb on open of the
dialog box and on close of it that is not freed up.
And hence doing this a couple of times takes up huge heap memory.
public class ImageOnClickListener implements OnClickListener {
String article_title ;
String article_url;
public ImageOnClickListener(String imageUrl, String title) {
article_title = title;
article_url = imageUrl;
}
@Override
public void onClick(View v) {
View layout = null;
AlertDialog.Builder imageDialog = new
AlertDialog.Builder(getActivity());
LayoutInflater inflater =
(LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.image_fragment, null);
TextView articleTitle =
(TextView)layout.findViewById(R.id.image_title);
articleTitle.setText(article_title);
articleTitle.setTextSize(MainActivity.fontSize +10);
articleTitle.setTextColor(getResources().getColor(
android.R.color.white));
URL imageUri = null;
try {
imageUri = new URL(article_url);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bitmapImage = null;
try {
bitmapImage =
BitmapFactory.decodeStream(imageUri.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
WindowManager wm = (WindowManager)
getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight();
int w = (int) (width*0.8);
int h = (int) (height*0.8);
ImageView imageObject =
(ImageView)layout.findViewById(R.id.image_main);
int imgWidth = bitmapImage.getWidth();
int imgHeight = bitmapImage.getHeight();
int ratio = w/imgWidth;
Bitmap.createScaledBitmap(bitmapImage,
imgWidth*ratio,imgHeight*ratio, true);
imageObject.setImageBitmap(bitmapImage);
RelativeLayout.LayoutParams imageParams = new
RelativeLayout.LayoutParams(w,h);
imageObject.setLayoutParams(imageParams);
alertDialog = imageDialog.setView(layout).create();
int dialogWidth = (int) (width*0.9);
int dialogHeight = (int) (height*0.9);
alertDialog.show();
alertDialog.getWindow().setLayout(dialogWidth,dialogHeight);
}
}
Basically I was looking for a way to free up that memory on dismiss of the
dialog.
No comments:
Post a Comment