2012-07-15 91 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(); 
       } 

      }