OutOfMemoryException は、画像が原因である可能性が最も高いです。
写真付きのホテルのリストを表示したいとしましょう。ホテル情報を XML 形式で取得し、リスト (または同様の構造) に保存します。ホテル クラスには次のようなメンバーがURL pictureURL
あり、そのようなメンバーWeakReference<Drawable> picture
は必要になるまで null になります。
AsyncTask
getView() メソッドでイメージのダウンロードを開始するようにリスト アダプタを作成し(picture が null を指している場合)、それをリスト内の ImageView と の両方に設定できますHotel.picture
。
Hotel.picture は弱参照であるため、画像が画面から消えると、ImageViews
再利用さ れてメモリが解放されます。
getView メソッドには、次のようなものが含まれる場合があります。
private class MyCustomAdapter extends BaseAdapter {
...
List<Hotel> hotelList;
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
Hotel hotel = hotelList.get(position);
ImageView ivHotelPic = //your image view from the list (child of 'view')
...
if (hotel.picture == null || hotel.picture.get() == null){
new DownloadImageTask(hotel,ivHotelPic).execute(hotel.pictureURL)
}
else{
ivHotelPic.setImageDrawable( hotel.picture.get() );
}
return view;
}
}
private class DownloadImageTask extends AsyncTask<URL, Integer, Drawable> {
Hotel hotel;
ImageView imageView;
DownloadImageTask(Hotel hotel,ImageView imageView){
this.hotel = hotel;
this.imageView = imageView;
}
protected Drawable doInBackground(URL... urls) {
assert urls.length == 1;
Drawable image = //download image from urls[0] (or hotel.pictureURL);
return image;
}
protected void onPostExecute(Drawable result) {
imageView.setImageDrawable(result);
hotel.picture = new WeakReference<Drawable>(result);
}
}
アクティビティが終了するまで画像を保持したい場合は、通常の参照を使用することもできますが、これにより、あまりにも多くの画像がダウンロードされたときに OutOfMemory が発生する可能性があります。