2013-01-16 32 views
1

我必須下載一些圖像並使用圖庫進行顯示。對於我用於圖庫的圖像適配器,我必須使用Async任務開始下載get view方法中的圖像。我的問題是,我不能將下載的圖像視圖返回到調用函數。由於networkonmainthread異常,我不能使用主線程下載。使用異步任務下載圖像並將其顯示在圖庫中

GalleryActivity

public class GalleryActivity extends Activity { 

    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.gallery); 
     ((Gallery) findViewById(R.id.gallery)).setAdapter(new ImageAdapter(this)); 
    } 

圖片適配器

public class ImageAdapter extends BaseAdapter { 

    public View getView(int position, View convertView, ViewGroup parent) {  
     new galleryBackground().execute(Integer.toString(position)); 
     ImageView i =null; 
     return i; 
    } 

} 

畫廊

public class galleryBackground extends AsyncTask<String, Integer, String> { 
    Bitmap bm;  
    public String[] myRemoteImages = { ....}; 
    ImageView i = new ImageView(GalleryActivity.this); 

    @Override 
    protected String doInBackground(String... arg0) { 
     try { 
      URL aURL = new URL(myRemoteImages[Integer.parseInt(arg0[0])]); 
      URLConnection conn = aURL.openConnection(); 

      conn.connect(); 
      InputStream is = conn.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      bm = bitmapFactory.decodeStream(bis); 
      bis.close(); 
      is.close(); 
     } 

    @Override  
    protected void onPostExecute(String result) { 
    i.setImageBitmap(bm); 
    i.setScaleType(ImageView.ScaleType.FIT_CENTER); 
    i.setLayoutParams(new Gallery.LayoutParams(150, 150)); 
    // i have to return this Image view to the calling function   
    super.onPostExecute(result); 
} 

回答

1

您的AsyncTask更改爲

AsyncTask<String, Integer, Bitmap> 

這將返回位圖和onPostExecute使用 您已經通過位置的位圖,這樣onPostExecute可以

yourlist.getItem(your position) and set the bitmap 
+1

謝謝你..現在工作.. :) –

1

你應該返回bm from doingBackground();

@Override 
protected String doInBackground(String... arg0) { 
    try{ 
     URL aURL = new URL(myRemoteImages[Integer.parseInt(arg0[0])]); 
     URLConnection conn = aURL.openConnection(); 
     conn.connect(); 
     InputStream is = conn.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     bm = bitmapFactory.decodeStream(bis); 
     bis.close(); 
     is.close(); 
     return bm; 
    } 
} 
+0

這是工作的罰款..Thank你.. :) –

+0

一些額外的信息:有時URLConnection類可以掛,所以一定要設定超時你的URLConnection對象。此外,如果在加載圖像時它被毀壞,它將保留對您的活動的引用。考慮切換到下面提到的庫,或者在你的AsyncTask中將你的ImageView引用置零。 – WindyB

2

該庫將解決你的問題:

https://github.com/xtremelabs/xl-image_utils_lib-android

從該回購中將JAR拉入您的項目中。

在Activity/Fragment中實例化一個ImageLoader並將其傳遞給適配器。

調用imageLoader.loadImage(imageView,url),並且一切都是由該系統爲您完成的。

維基可以告訴你如何將其插入