【问题标题】:Displaying multiple images using their URLs to listview with JSON使用它们的 URL 显示多个图像以使用 JSON 进行列表视图
【发布时间】:2026-01-01 01:35:02
【问题描述】:

我一直在尝试将我的图像 url 加载到一个列表视图中,这是第一个必须下载的列表视图,有人可以帮助我。

HashMap<String, String> map = new HashMap<String, String>();
 map.put("id", String.valueOf(i));
 map.put("name", "House name:" + json_data.getString("name"));
map.put("address", "Adress: " + json_data.getString("address"));

URL newurl = new URL(json_data.getString("imageUrl"));
 itmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(result).getContent());
 ImageView imagy = (ImageView)findViewById(R.id.image);
 imagy.setImageBitmap(bitmap); 
  map.put("img",bitmap);//error is here says convert bitmap to type string
  mylist.add(map);

【问题讨论】:

  • 这个错误有点说明你的问题是什么:你试图把一个 Bitmap 对象放入一个 HashMap&lt;String, String&gt; 对象中。

标签: android json image url listview


【解决方案1】:

你到底在用这段代码做什么?

 URL newurl = new URL(json_data.getString("imageUrl"));
            Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(result).getContent());
            ImageView imagy = (ImageView)findViewById(R.id.image);
              imagy.setImageBitmap(bitmap); 
             map.put("img",bitmap);//error is here says convert bitmap to type string

            mylist.add(map);

因为您每次都在执行 findViewById() 并设置图像位图。然后你在 mylist 中添加。

建议: 相反,我建议您仅将 URL 字符串添加到 HashMap 中:

String strImageURL = json_data.getString("imageUrl");
map.put("img",strImageURL );/

在为您的 ListView 定义自定义适配器时,只需在自定义适配器的 getView() 方法中执行上述操作(您可以通过扩展 BaseAdapter)。

建议 2: 如果要在 ListView 中实现图像的延迟加载,请查看 Fedor 在此处给出的答案:Android - How do I do a lazy load of images in ListView

【讨论】:

  • 问题是 Fedor 只处理静态图像,而我的是动态的。当我用我的 imageUrl[i](我从 json 获取)替换时,他的 mstrings(静态列表)不起作用并且关联图像的每个细节也是我遇到的问题。
  • 嘿嘿嘿....相反,您也可以将数组传递给自定义适配器。您只需要查看示例和 ImageLoader 类的用法即可。
【解决方案2】:

我希望,你实际的 HashMasp 是 HashMap map = new HashMap();

如果是这样,你只能添加字符串值。 试试下面的,

class House {
    int id;
    String houseName;
    String houseAddress;
    Bitmap image;
}

List<House> houseList = new ArrayList<House> ();

House houseObj = new House();

houseObj.id = i;
houseObj.houseName = "House name:" + json_data.getString("name");
houseObj.address = "Adress: " + json_data.getString("address");

URL newurl = new URL(json_data.getString("imageUrl"));
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(result).getContent());
ImageView imagy = (ImageView)findViewById(R.id.image);
imagy.setImageBitmap(bitmap); 

houseObj.image = bitmap;

houseList.add(houseObj);

在你的列表视图适配器中使用这个列表。

【讨论】:

  • 嘿,非常感谢曼恩!!!你拯救了我的一天...如果可能的话我会给出 +10,抱歉我只能给出 +1 :-)
最近更新 更多