我做了一个应用程序,可以告诉您进入该位置的天气..该API取自OpenWeatherMap.org并显示天气..我想显示图标,我也拿了图标ID并粘贴在链接..图像没有显示..
try {
DownloadTask downloadTask = new DownloadTask();
String city = weatherInput.getText().toString();
Log.i("City name",city);
//used to encode the entered input for url.. for example San Fransisco appears in url
//as San%20Fransisco ... and to enable that we use the encoder...
String encodedCity = URLEncoder.encode(city,"UTF-8");
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity +
"&appid=cd66504ca815ddc1971662a9f2147f84");
Log.i("Image id",icon);
ImageDownloader imageDownloader = new ImageDownloader();
myImage = imageDownloader
.execute("http://openweathermap.org/img/w/" + icon + ".png").get();
imageView.setImageBitmap(myImage);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
这是ImageDownloader类。 图标是一个全局变量,当我使用其他变量(如天气状况)解析API时,我得到了。
public class ImageDownloader extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... urls) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
return BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
请注意我在一个Activity中有两个AsyncTask类,所以如果它导致一些错误..我不知道它..