1

I want to show product image. Each products have 4 images. When I show image in ImageView then I got out of memory.

This is my code:

public class ImagesActivity extends Activity  {
private String styleCode,styleName;
private String strExecutive;
private Uri[] mUrls;  
String[] mFiles=null;  
private  Gallery g;
private ImageView picture;

public void onCreate(Bundle icicle)  {  
    super.onCreate(icicle);  
    setContentView(R.layout.image_view); 

    Bundle b = getIntent().getExtras();
    styleCode =  b.getString("styleCode");
    styleName =b.getString("styleCode");

    setTitle(styleName);

    SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_PRIVATE);
    strExecutive = myPrefs.getString("Executive", "");

    picture = (ImageView) findViewById(R.id.picture);

    Button picCancel = (Button)findViewById(R.id.picCancel);
    picCancel.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            Bundle bundle = new Bundle(); 
            bundle.putString("Activity", "ImagesActivity");
            i.putExtras(bundle);
            finish();
        }
    });

    String folderPath = Environment.getExternalStorageDirectory() + "/"+strExecutive+"/"+styleCode+"/";
    File filePath = new File(folderPath);
    File[] imagelist = filePath.listFiles(new FilenameFilter(){  
        public boolean accept(File dir, String name)  {  
            return ((name.endsWith(".jpg"))||(name.endsWith(".png")));
        }  
    });  
    mFiles = new String[imagelist.length];  

    for(int i= 0 ; i< imagelist.length; i++)  
    {  
        mFiles[i] = imagelist[i].getAbsolutePath();  
    }  
    mUrls = new Uri[mFiles.length];  

    for(int i=0; i < mFiles.length; i++)  
    {  
        mUrls[i] = Uri.parse(mFiles[i]);     
    }     

    g = (Gallery) findViewById(R.id.gallery);  
    g.setAdapter(new ImageAdapter(this));  
    g.setFadingEdgeLength(40); 



    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            Toast.makeText(arg1.getContext()," Image is available to this style"  + arg2,Toast.LENGTH_LONG).show();
            getLargeImage(arg2);
        }
    });
}  


public void getLargeImage(int position) {
    Uri pickedUri =mUrls[position];
    Bitmap pic = null;
    String imgPath = "";
    String[] medData = { MediaStore.Images.Media.DATA };
    Cursor picCursor = managedQuery(pickedUri, medData, null, null, null);
    if(picCursor!=null)
    {
        int index = picCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        picCursor.moveToFirst();
        imgPath = picCursor.getString(index);
    }
    else
        imgPath = pickedUri.getPath();
        if(pickedUri!=null) {

            int targetWidth = 600;
            int targetHeight = 400;
            BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
            bmpOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgPath, bmpOptions);

            int currHeight = bmpOptions.outHeight;
            int currWidth = bmpOptions.outWidth;
            int sampleSize = 1;
            if (currHeight>targetHeight || currWidth>targetWidth) 
            {
                if (currWidth>currHeight)
                    sampleSize = Math.round((float)currHeight/(float)targetHeight);
                else 
                    sampleSize = Math.round((float)currWidth/(float)targetWidth);
            }
            bmpOptions.inSampleSize = sampleSize;
            bmpOptions.inJustDecodeBounds = false;
            pic = BitmapFactory.decodeFile(imgPath, bmpOptions);
            Drawable toRecycle= picture.getDrawable();
            if (toRecycle != null) {
                ((BitmapDrawable)picture.getDrawable()).getBitmap().recycle();
            }
            picture.setImageBitmap(pic);
            picture.setScaleType(ImageView.ScaleType.FIT_CENTER);
       }

}
public class ImageAdapter extends BaseAdapter{  
    int mGalleryItemBackground;  
    public ImageAdapter(Context c)  {     
        mContext = c;    

        TypedArray styleAttrs = mContext.obtainStyledAttributes(R.styleable.PicGallery);
        mGalleryItemBackground = styleAttrs.getResourceId(
                R.styleable.PicGallery_android_galleryItemBackground, 0);
        styleAttrs.recycle();
    }  
    public int getCount(){  
        return mUrls.length;  
    }  
    public Object getItem(int position){  
        return position;  
    }  
    public long getItemId(int position) {  
        return position;  
    }  
    public View getView(int position, View convertView, ViewGroup parent){  
        ImageView i = new ImageView(mContext);  
        Drawable toRecycle= i.getDrawable();
        if (toRecycle != null) {
            ((BitmapDrawable)i.getDrawable()).getBitmap().recycle();
        }

        i.setImageURI(mUrls[position]);  
        i.setScaleType(ImageView.ScaleType.FIT_XY);  
        i.setLayoutParams(new Gallery.LayoutParams(260, 210));  
        return i;  
    }     
    private Context mContext;  
    }     

Error say :

     06-13 17:51:26.042: E/AndroidRuntime(27358): FATAL EXCEPTION: main
06-13 17:51:26.042: E/AndroidRuntime(27358): java.lang.OutOfMemoryError
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:582)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:380)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:413)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.graphics.drawable.Drawable.createFromPath(Drawable.java:880)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.ImageView.resolveUri(ImageView.java:569)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.ImageView.setImageURI(ImageView.java:340)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at xont.sdfd.controller.sales.ImagesActivity$ImageAdapter.getView(ImagesActivity.java:225)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:192)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.View.measure(View.java:12775)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4709)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1385)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:670)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:563)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.View.measure(View.java:12775)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4709)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.View.measure(View.java:12775)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4709)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.View.measure(View.java:12775)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4709)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1385)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:670)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:563)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.View.measure(View.java:12775)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4709)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2240)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.View.measure(View.java:12775)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1092)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2505)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.os.Looper.loop(Looper.java:137)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at android.app.ActivityThread.main(ActivityThread.java:4514)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at java.lang.reflect.Method.invokeNative(Native Method)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at java.lang.reflect.Method.invoke(Method.java:511)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
06-13 17:51:26.042: E/AndroidRuntime(27358):    at dalvik.system.NativeStart.main(Native Method)

I have tested my application samsung galaxy 2 7.0 tab.

Please tell me , in my code what is an issue?

Thanks in advance

3

2 Answers 2

1

You are performing the sampling only once. That could be the reason you are getting OOM.

Try this:

   if (currHeight>targetHeight || currWidth>targetWidth) 
        {
            if (currWidth>currHeight)
                sampleSize = Math.round((float)currHeight/(float)targetHeight);
            else 
                sampleSize = Math.round((float)currWidth/(float)targetWidth);
        }

        final float totalPixels = currWidth * currHeight;
        // Anything more than 2x the requested pixels, sample down further

        final float totalReqPixelsCap = targetWidth * targetHeight * 2;
        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

public View getView(int position, View convertView, ViewGroup parent){  
    ImageView i = convertView;  
    Drawable toRecycle= i.getDrawable();
    if (toRecycle != null) {
        ((BitmapDrawable)i.getDrawable()).getBitmap().recycle();
    }

    i.setImageURI(mUrls[position]);  
    i.setScaleType(ImageView.ScaleType.FIT_XY);  
    i.setLayoutParams(new Gallery.LayoutParams(260, 210));  
    return i;  
}     

Also, try increasing your VM heap size to allow your sandboxed environment to allocate more memory.

2 Comments

already i wrote in my code also & android:largeHeap="true" in manifeast file also
if you use android:largeHeap="true" heap is large..larger the heap more frequent garbabge collection more frequent pause times. so you should be careful in using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.