gridAdapter中的OutOfMemoryError

时间:2015-06-05 09:12:05

标签: android gridview imageview adapter

我正在尝试为我的gridView创建适配器,它应该包含我在gallery中选择的照片。但我在“返回行”

行中跟随OutOfMemoryError
public class GridViewAdapter extends ArrayAdapter<String> {
    private Context context;
    private int layoutResourceId;
    private ArrayList<String> images_urls;

public GridViewAdapter(Context context, int layoutResourceId, ArrayList<String> images_urls) {
    super(context, layoutResourceId, images_urls);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.images_urls = images_urls;
}

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

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.image = (ImageView) row.findViewById(R.id.grid_image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

     File f = new File(images_urls.get(position));  
     Uri imageUri = Uri.fromFile(f);
     holder.image.setImageURI(imageUri);
    return row;
}


static class ViewHolder {
    ImageView image;
}
}

我只是不知道是什么造成了错误。有人可以帮我解决吗?

2 个答案:

答案 0 :(得分:1)

图像加载是一种比这更复杂的方式,如果你对它感兴趣,你可以在线阅读很多主题/博客/等。但StackOverflow是一个直接的问答,所以,

要解决此问题,请导入此库:https://github.com/square/picasso

然后替换这些行:

File f = new File(images_urls.get(position));  
Uri imageUri = Uri.fromFile(f);
holder.image.setImageURI(imageUri);

使用:

Picasso
  .with(holder.image.getContext())
  .load(image_urls.get(position))
  .into(holder.image);

这个库将负责妥善管理内存。请务必进一步检查库API,因为您可以添加额外的命令来调整屏幕上的图像大小,以便使用更少的内存。

答案 1 :(得分:0)

AndroidManifest.xml

android:largeHeap =“true”添加到您的&lt;申请&gt;

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<application
    android:largeHeap="true"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.sample.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

为了避免OutofMemory错误,您应该使用通用图片加载器Link或Picasso Library Link