2012-07-15 96 views
0

我已經搜索並嘗試了很多不同的方法來顯示從ListView中的圖像,但我無法讓我的代碼工作。下面是我的代碼下載圖像,然後顯示它們在一個ListView,但不知何故,它不工作。Android - 如何在ListView中顯示來自URL的圖像?

private Drawable LoadImageFromWebOperations(String url) 
    { 
     try 
     { 
      InputStream is = (InputStream) new URL(url).getContent(); 
      Drawable d = Drawable.createFromStream(is, "src name"); 
      return d; 
     } 
     catch (Exception e) 
     { 
      return null; 
     } 
    } 

這裏是我的代碼來調用上面的函數

Drawable image = LoadImageFromWebOperations("http://10.0.0.5/images/logo.jpg"); 

這個我把它變成一個地圖後,然後把映射到一個名爲「產品列表」的ArrayList

map.put("avatar", image); 
productsList.add(map); 

最後我用SimpleAdapter在ListView中顯示HashMap

ListAdapter adapter = new SimpleAdapter(
    Home.this, productsList, 
    R.layout.list_item, new String[] { TAG_PID, 
    TAG_NAME, "url", "avatar"}, 
    new int[] { R.id.pid, R.id.name, R.id.url, R.id.avatar }); 

我的應用程序顯示除圖像以外的所有內容。我在Google上搜索了這個問題,但無法獲得幫助。任何幫助表示讚賞?

+0

您是否驗證了LoadImageFromWebOperation s不返回null? – tiguchi 2012-07-15 16:32:38

+0

@Nobu是的,我在TextView中輸出結果,它給了[email protected]_。 – user1526938 2012-07-15 17:33:44

回答

0

這一定會幫助你,

CustomAdapter adapter = new CustomAdapter(Home.this, productsList, R.layout.list_item, 
new String[] { TAG_PID,TAG_NAME, "url", "avatar"}, 
new int[] { R.id.pid, R.id.name, R.id.url, R.id.avatar }); 

創建延伸SimpleAdapter一個CustomAdapter類,覆蓋getView()方法,

@Override 
public View getView(int position, View convertView, ViewGroup parent) 
{ 
    View v = super.getView(position, convertView, parent); 
    HashMap<String, Object> hm = (HashMap<String, Object>) super.getItem(position); 
    ImageView image = (ImageView) v.findViewById(R.id.yourImageID); 
    TextView txt1 = (TextView) v.findViewById(R.id.yourtxtID1); 
    TextView txt2 = (TextView) v.findViewById(R.id.yourtxtID2); 
    TextView txt3 = (TextView) v.findViewById(R.id.yourtxtID3); 


    image.setImageDrawable((Drawable) hm.get("avatar")); 
    txt1.setText(hm.get("TAG_PID").toString()); 
    txt2.setText(hm.get("TAG_NAME").toString()); 
    txt3.setText(hm.get("url").toString()); 

    return v; 

} 

讓我知道,如果問題仍然存在。 。

1
try 

if (image != null) { 

       Bitmap bitimage = null; 
       BitmapFactory.Options options = new BitmapFactory.Options(); 
       options.inSampleSize = 1; 
       try { 

              //bitimage = BitmapFactory.decodeStream((InputStream) new URL(data.getThumbnail().toString().trim().toString()).getContent(), null, options); 
              bitimage = BitmapFactory.decodeStream((InputStream) new URL(ed).getContent(), null, options); 
        image.setImageBitmap(bitimage); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

      } 
相關問題