adn*_*eal 3 java android bitmap last.fm
我正在尝试从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();
}
}
Run Code Online (Sandbox Code Playgroud)
您尝试使用的API会返回XML,而不是图像.您需要解析响应并从响应中选择适当的图像URL.
该API文档是很透彻,并观看了每个人最喜爱的艺术家,样本响应尼山,会给你足够的方向找到一个合适的图像显示.
编辑:有关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;
}
Run Code Online (Sandbox Code Playgroud)
和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;
}
}
Run Code Online (Sandbox Code Playgroud)