我已经为gridView编写了一个适配器来显示从互联网上下载的照片,部分代码列如下
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
public ArrayList<Drawable> drawablesFromUrl = new ArrayList<Drawable>();
public ImageAdapter(Context c) {
mContext = c;
}
public void addItem(Drawable item) {
drawablesFromUrl.add(item);
}
public int getCount() {
return drawablesFromUrl.size();
}
public Drawable getItem(int position) {
return drawablesFromUrl.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(drawablesFromUrl.get(position));
return imageView;
}//View getView
}//class ImageAdapter
它工作正常,下载的照片存储在ArrayList“drawablesFromUrl.get(position)”
现在我写了一个意图打开另一个活动,在imagView中显示一张单独的照片,部分代码列表如下:
SitePhotoGallery pg = new SitePhotoGallery();
ImageAdapter imageAdapter = pg.new ImageAdapter(this);
Drawable dPhoto=imageAdapter.drawablesFromUrl.get(position); //(ERROR in this line)
BitmapDrawable bPhoto = (BitmapDrawable) dPhoto;
Bitmap snoop = bPhoto.getBitmap();
//Bitmap snoop = BitmapFactory.decodeResource(getResources(),imageAdapter.mThumbIds[position]);
img.setImageBitmap(snoop);
img.setMaxZoom(4f);
setContentView(img);
它提示错误:
07-11 15:22:11.458:E / AndroidRuntime(12856):java.lang.RuntimeException:无法启动活动
ComponentInfo {com.android.mcsis / com.android.mcsis.SitePhotoFullScreen}:java.lang.IndexOutOfBoundsException:索引0无效,大小为0
我猜arraylist imageAdapter.drawablesFromUrl.get(position);
是空的。我出错了什么?
答案 0 :(得分:0)
ImageAdapter imageAdapter = pg.new ImageAdapter(this);
我认为您正在创建ImageAdapter内部类的新实例。 因此,先前存储的arraylist位图数据将丢失,因为它曾经属于不同的对象。
如果您希望在整个应用程序中保留一些数据,请尝试使用Application类对象。它非常简单和漂亮。并且可以得到它的实例 通过context.getApplicationContext()。