Android 从URL显示图像

Android 从URL显示图像,android,Android,我在显示从URL获取到ImageView的图像时遇到一些问题。用我目前掌握的代码,我什么也得不到。这个代码有问题吗 Drawable img = image.LoadImageFromWeb(icon); imageView.setImageDrawable(img); public static Drawable LoadImageFromWeb(String iconId) { try { String url = "http://ddragon.l

我在显示从URL获取到ImageView的图像时遇到一些问题。用我目前掌握的代码,我什么也得不到。这个代码有问题吗

Drawable img = image.LoadImageFromWeb(icon);
imageView.setImageDrawable(img);

public static Drawable LoadImageFromWeb(String iconId) {
        try {
            String url = "http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId + ".png";
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable icon = Drawable.createFromStream(is, "src name");
            return icon;
        } catch (Exception e) {
            return null;
        }
    }
试试这个功能

  private void downloadImage() 
  {
    Bitmap bitmap = null;
    try {
            URL urlImage = new 
   URL("http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId +
  ".png");
            HttpURLConnection connection = (HttpURLConnection)
    urlImage.openConnection();
            InputStream inputStream = connection.getInputStream();
            //****bitmap is your image*****
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}
并使用asyncTask等待下载图像,如下所示

      private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {     

    @Override
    protected Void doInBackground(Void... params) {
        //get the random string from prefs
        if (context != null)
            downloadImage();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //do what you want after the image downloaded
    }
}
私有类Asyn_SaveData扩展异步任务{
@凌驾
受保护的Void doInBackground(Void…参数){
//从prefs获取随机字符串
if(上下文!=null)
下载图像();
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
//下载图像后执行所需操作
}
}

注意:AsyncTask必须是子类的,在doInBackground完成其作业后,它会自动调用onPostExecute

我建议您为此使用一个库,例如Square。在这种情况下,什么是categorie.length?问题是我必须等待AsyncTask完成才能获取iconId,因此,这将导致错误NetworkInMainThreadException。你会推荐什么?如果我明白你的意思,你需要在asynctask中下载图像,检查我的编辑plz