3

我正在尝试从 Last.fm 获取艺术家图像并将其应用到ImageView,但没有返回任何图像。我不确定我在这里做错了什么。

private void setLastFmArtistImage() {

    try {
        String imageurl = "http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="
                + URLEncoder.encode("Andrew Bird")
                + "&api_key="
                + APIKEY
                + "&limit=" + 1 + "&page=" + 1;
        InputStream in = null;

        Log.i("URL", imageurl);
        URL url = new URL(imageurl);
        URLConnection urlConn = url.openConnection();

        HttpURLConnection httpConn = (HttpURLConnection) urlConn;

        httpConn.connect();

        in = httpConn.getInputStream();

        Bitmap bmpimg = BitmapFactory.decodeStream(in);
        mArtistBackground.setImageBitmap(bmpimg);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
4

1 回答 1

6

您尝试使用的 API 返回 XML,而不是图像。您需要解析响应并从响应中选择适当的图像 URL。

API 文档非常详尽,查看每个人最喜欢的艺术家Benny Hill的示例响应将为您提供足够的指导来找到合适的图像来显示。

编辑:对于 API 的示例,您可以查看官方Last.fm 客户端- 但请注意,这是 GPL3 许可的东西,除非您想发布您的源代码,否则您不应该过多地使用复制和粘贴。

编辑(再次):对于一个没有被 GPL3污染的例子,试试这个:

(该示例使用JSoup,友好的 XML 解析器)

public List<LastFmImage> getLastFmImages(String artistName, int limit, int page) throws IOException {
    String apiUrl = "http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="
            + URLEncoder.encode(artistName)
            + "&api_key="
            + APIKEY
            + "&limit=" + limit + "&page=" + page;

    Document doc = Jsoup.connect(apiUrl).timeout(20000).get();
    Elements images = doc.select("images");

    ArrayList<LastFmImage> result = new ArrayList<LastFmImage>();
    final int nbrOfImages = images.size();
    for (int i = 0; i < nbrOfImages; i++) {
        Element image = images.get(i);
        String title = image.select("title").first().text();
        Elements sizes = image.select("sizes").select("size");
        final int nbrOfSizes = sizes.size();
        for (int j = 0; j < nbrOfSizes; j++) {
            Element size = sizes.get(i);

            result.add(new LastFmImage(title, size.text(),
                    size.attr("name"),
                    Integer.parseInt(size.attr("width")),
                    Integer.parseInt(size.attr("height"))));
        }
    }
    return result;
}

和 LastFmImage 类:

public class LastFmImage {
    public String mTitle;
    public String mUrl;
    public String mName;
    public int mWidth;
    public int mHeight;

    public LastFmImage(String title, String url, String name, int width, int height) {
        mTitle = title;
        mUrl = url;
        mName = name;
        mWidth = width;
        mHeight = height;
    }
}
于 2012-01-25T07:42:17.357 回答