2012-12-01 134 views
2

我一直有很多麻煩使用適配器來正確地顯示我的圖像到我的imageView。所以基本上我有一個JSON字符串,我通過解析來獲取每個圖像的URL。然後,我想以列表視圖的方式顯示每個圖像的標題。Android動態顯示圖像

我在網上發現了這個代碼,當它只需要顯示一個圖像時,它可以很好地工作,但當我必須動態地執行此操作時,它不起作用。任何人都有一些關於如何使其運行的好建議?我附上部分代碼以供參考。

謝謝!!!

//results => JSON string 
ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>(); 
for(int i = 0; i < results.length(); i++){ 
JSONObject c = results.getJSONObject(i); 

// Storing each json item in variable 
cover = c.getString(TAG_COVER); 
String title = c.getString(TAG_TITLE); 

try { 

    URL urlS = new URL(cover); 
    new MyDownloadTask().execute(urlS); 

    }catch (MalformedURLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 
// creating new HashMap 
HashMap<String, Object> map = new HashMap<String, Object>(); 

// adding each child node to HashMap key => value 
map.put(TAG_COVER, cover); 
map.put(TAG_TITLE, title); 
// adding HashList to ArrayList 
resultList.add(map); 
} 
} 
    } catch (JSONException e) { 
e.printStackTrace(); 
    } 

/** 
* Updating parsed JSON data into ListView 
* */ 
ListAdapter adapter = new SimpleAdapter(this, resultList, 
     R.layout.list_item, 
     new String[] {TAG_TITLE}, new int[] { 
     R.id.title}); 

setListAdapter(adapter); 

這裏是圖像下載的代碼,我發現:

private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> { 
    @Override 
    protected Bitmap doInBackground(URL... params) { 
     URL url = params[0]; 
     Bitmap bitmap = null; 
     try { 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 
      InputStream is = connection.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      bitmap = BitmapFactory.decodeStream(bis); 
      bis.close(); 
      //is.close(); THIS IS THE BROKEN LINE 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } 

     return bitmap; 
    } 


    protected void onPostExecute(Bitmap bitmap) { 
     if (bitmap != null) { 
      ImageView myImage = (ImageView) findViewById(R.id.list_image); 
      myImage.setImageBitmap(bitmap); 
     } else { 
      Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show(); 
     } 

    }  
} 

回答

1

有相當不錯的庫調用AQuery。你可以使用它,簡單通過書面方式只有2行代碼獲取所有這些東西,再加上它會緩存爲你的所有圖像,這是非常好的especcially,如果你使用的是他們在ListView

AQuery aq = new AQuery(activity); 
aq.id(R.id.image).image(url, false, true); 

而且我認爲它會最好使用CustomAdapter。我不確定是否可以使用SimpleAdapter來處理這種情況。 希望這會幫助你。

+0

AQuery非常棒。將它整合到我的圖書館。 – anticafe

+0

Yeap這是非常好的) – Evos