2011-07-04 33 views
0

我必須從網址下載圖片,然後在UI上的圖片視圖中顯示下載的圖片。 對於這個我使用下述代碼:通過多線程下載圖片並非在Android中工作

public class ShowUIData extends AsyncTask<Void, Void, Void> { 
    String productvalues[]; 
    Drawable productimagebitmap; 

    @Override 
    protected Void doInBackground(Void... params) { 
     productvalues = hb.getProductDetailsWithJson(id + 1); 
     if (productvalues != null) { 
      productimagebitmap = getImage(productvalues[3]); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     if (productvalues != null) { 
      // Set the values obtained from the database. 
      // Check if image returned from URL is not null. 
      if (productimagebitmap != null) { 
       ImageView productimage = (ImageView) findViewById(R.id.productimage); 
       productimage.setImageDrawable(productimagebitmap); 
      } 
     } 
     dismissDialog(); 
    } 

    // Download image from URL obtained for database. 
    private Drawable getImage(String address) { 
     try { 
      Log.i("product details", "starting image download"); 
      URL url = new URL(address); 
      URLConnection conn = url.openConnection(); 
      conn.connect(); 
      InputStream is = conn.getInputStream(); 
      Drawable d = Drawable.createFromStream(is, "src name"); 
      is.close(); 
      return d; 
     } catch (Exception e) { 
      Log.i("the url", address); 
      e.printStackTrace(); 
      return getApplicationContext().getResources().getDrawable(
        R.drawable.noimage); 
     } 
    } 

一個有效的URL被傳遞到的getImage功能,沒有異常被拋出,仍像未在ImageView的設置。當我調試我的應用程序時,圖像設置正確。 我相信我需要把一個阻塞調用,直到圖像下載,然後調用image.setImageDrawable。

這裏發生了什麼問題。我無法弄清楚爲什麼我無法加載任何圖像,爲什麼只有當我調試時,我看到一個圖像?

謝謝你提前。

回答

0

你應該試試this的例子。它運行時從URL中獲取圖像,並在列表視圖中顯示它。我認爲這會幫助你。

0

非UI線程無法更新UI組件。使用處理程序來更新UI組件。

+0

onPostExecute在UI線程上執行。所以我沒有做任何事情的UI線程。 – user590849