O
O
Oleg Reksha2014-03-26 12:05:45
Android
Oleg Reksha, 2014-03-26 12:05:45

How to load images in ImageView with Url?

The method itself:

private Bitmap downloadImage(String urlStr){
  Bitmap result;
try {
  URL url = new URL(urlStr);
  HttpURLConnection connect = (HttpURLConnection)url.openConnection();
  connect.setAllowUserInteraction(false);
  connect.setInstanceFollowRedirects(true);
  connect.setRequestMethod("GET");
  connect.connect();
  
  InputStream input = connect.getInputStream();
  result = BitmapFactory.decodeStream(input);
  
} catch (Exception e) {
  Toast T = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
  T.show();
  return null;
}
  return result;
}

An error occurs when trying to create a connection.
permission INTERNET set.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mop9k, 2014-04-09
@OlegReksha

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
              InputStream in = new java.net.URL(urldisplay).openStream();
              mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
      	bmImage.setImageBitmap(result);
      }
  }

new DownloadImageTask((ImageView) findViewById(R.id.imageview)).execute(ImageUrl);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question