2012-07-11 62 views
0

我已經寫了一個適配器爲GridView顯示的照片是從網上和部分代碼下載被列爲遵循Android的IndexOutOfBound異常

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(位置)」

現在我已經寫了一個意向來打開另一個活動在代碼的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: Unable to start activity
ComponentInfo{com.android.mcsis/com.android.mcsis.SitePhotoFullScreen}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

我猜的ArrayList imageAdapter.drawablesFromUrl.get(position);是空的。任何我錯了?

回答

0

ImageAdapter imageAdapter = pg.new ImageAdapter(this);

我想你正在創建ImageAdapter內部類的新實例。 因此,先前存儲的陣列列表位圖數據將因爲它用於屬於不同的對象而丟失。

而不是嘗試使用應用程序類對象,如果你想保持一些數據在整個應用程序中活着。它非常簡單而漂亮。並且可以通過context.getApplicationContext()獲取它的實例 。

+0

能否詳細說明如何使用Application類對象?我不知道如何使用,謝謝! – user1411475 2012-07-11 08:02:41

+0

請看下面的鏈接.http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/ – Shachillies 2012-07-11 09:26:51