简体   繁体   English

实施图片库时出现内存不足异常

[英]Out of memory exception while implementing image gallery

I am writing a code to implement a small image gallery in android device. 我正在编写代码以在android设备中实现小型图片库。 My code is as follows. 我的代码如下。 The code is working but it is giving out of memory exception please help. 该代码正在运行,但发出内存不足异常,请提供帮助。 iam fresh to android. IAM新鲜到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

这篇文章真的可以帮到您,还有一些Google I / O视频讨论了这个主题,请看一看: 2013年

use convertView is not null then try to else 使用convertView不为null,然后尝试其他

     @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;

    }

Its better to use the Universal Image Loader library already available for this purposes. 最好使用为此目的已经可用的Universal Image Loader库。 You need not bother about anything, just go through their documentation. 您无需担心任何事情,只需阅读它们的文档即可。 Refer here: https://github.com/nostra13/Android-Universal-Image-Loader 请参阅此处: https : //github.com/nostra13/Android-Universal-Image-Loader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM