Nate
Nate

Reputation: 412

Displaying an image from URL

I'm having some troubles displaying an image I am fetching from a URL into an ImageView. With the code I have at the moment, I am getting absolutely nothing. Is there a problem with this code?

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;
        }
    }

Upvotes: 0

Views: 76

Answers (1)

wael
wael

Reputation: 454

try this function

  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();
        }
}

and use asyncTask to wait until downloading the image like this

      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
    }
}

Note: AsyncTask must be subClassed, and after the doInBackground finish its job it calls automatically the onPostExecute

Upvotes: 1

Related Questions