问题
I'm trying create adapter for my gridView which should contains photo, which I chose in gallery. But I have following OutOfMemoryError in line "return row"
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;
}
}
And I just don't know what makes error. Could someone help me solve it?
回答1:
Image loading is a way way more complex thema than this, if you're interested on it, there's lots of topics/blog/etc you can read online. But StackOverflow is a direct question-answer, so,
To fix the issue, import this library: https://github.com/square/picasso
and then replace those lines:
File f = new File(images_urls.get(position));
Uri imageUri = Uri.fromFile(f);
holder.image.setImageURI(imageUri);
with:
Picasso
.with(holder.image.getContext())
.load(image_urls.get(position))
.into(holder.image);
this library will take care of proper managing the memory. Make sure to further check the library API as you can put extra commands to resize the image on-screen so it uses less memory.
回答2:
In Your AndroidManifest.xml
add android:largeHeap="true" to your < application >
<?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>
And to avoid OutofMemory Error you should use Universal Image Loader Link or Picasso Library Link.
来源:https://stackoverflow.com/questions/30662672/outofmemoryerror-in-my-gridadapter