Out of memory exception while implementing image gallery

坚强是说给别人听的谎言 提交于 2019-12-08 13:15:13

问题


I am writing a code to implement a small image gallery in android device. My code is as follows. The code is working but it is giving out of memory exception please help. iam fresh to android. thanks in advance.

public class GalleryActivity extends Activity{
/*
 * Storage Variable
 */
private int count;
private Bitmap[] thumbnails;        //Images to be displayed
private String[] arrPath;           //Path of the images to be displayed
private ImageAdapter imageAdapter;  //Set how the images to be displayed

Cursor imagecursor;                 //To move through the query
Layout grid;

/*
 * Shows the Images in the form of a gallery
 */
@SuppressWarnings("deprecation")
public void showGallery() {
    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                columns,
                                null,
                                null, 
                                orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.thumbnails = new Bitmap[this.count];
    this.arrPath = new String[this.count];
    GridView imagegrid = (GridView) findViewById(R.id.PhotoGrid);
    imageAdapter = new ImageAdapter();
    imagegrid.setAdapter(imageAdapter);

    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i]= imagecursor.getString(dataColumnIndex);

    }
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();            // To know from where the activity was called
    String action = intent.getAction();
    String type = intent.getType();
    showGallery();
}

@Override
public void onLowMemory() {
    System.gc();
    System.out.println("Low Memory $$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
    super.onLowMemory();
}

/*
 * Unregister every resource before exiting
 * @see android.app.Activity#onDestroy()
 */
@Override
protected void onDestroy() {
    super.onDestroy();
    if(imagecursor != null){
        imagecursor.close();
    }
    if(socket != null){
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/*
 * Class        : ImageAdapter
 * Description  : Contains functions to populate the GridView to form an image
 */
public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return count;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView holder;
        convertView = mInflater.inflate(
        R.layout.one_image, null);
        holder = (ImageView)convertView.findViewById(R.id.PhotoImage);
        convertView.setTag(holder);
        holder.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                int id = v.getId();
                System.out.println(String.valueOf(id));
                Intent intent = new Intent(GalleryActivity.this, ViewImage.class);
                intent.putExtra("path", arrPath[id]);
                intent.putExtra("command", "upload");
                System.out.println(arrPath[id]);
                startActivity(intent);
            }
        });
        holder.setImageBitmap(thumbnails[position]);
        holder.setId(position);
        return convertView;
    }
}// ImageAdapter

public class SimpleGestureDetector extends SimpleOnGestureListener implements OnClickListener{

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return super.onDoubleTap(e);
    }

    @Override
    public void onClick(View arg0) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                System.out.println("Left");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

}// GalleryActivity

回答1:


use convertView is not null then try to else

     @Override
            public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder2;
        if (convertView == null) {

                holder2 = new ViewHolder();
                convertView = mInflater.inflate(
                R.layout.one_image, null);
                holder1 = (ImageView)convertView.findViewById(R.id.PhotoImage);
                convertView.setTag(holder1);

              }
           else {

            holder2= (ViewHolder) convertView .getTag();
            }

                return convertView;
            }

private static class ViewHolder {
        ImageView holder1;

    }



回答2:


This post will really help you out, there is also some Google I/O videos discussing this subject, take a look: 2013 one




回答3:


Its better to use the Universal Image Loader library already available for this purposes. You need not bother about anything, just go through their documentation. Refer here: https://github.com/nostra13/Android-Universal-Image-Loader



来源:https://stackoverflow.com/questions/17020854/out-of-memory-exception-while-implementing-image-gallery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!