Load image from url

前端 未结 16 2186
独厮守ぢ
独厮守ぢ 2020-11-22 05:12

I have an image URL. I want to display an image from this URL in an ImageView but I am unable to do that.

How can this be achieved?

16条回答
  •  时光取名叫无心
    2020-11-22 05:26

    The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.

    To use an asynctask to add this class at the end of your activity:

    private class DownloadImageTask extends AsyncTask {
      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);
      }
    }
    

    And call from your onCreate() method using:

    new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute(MY_URL_STRING);
    

    Dont forget to add below permission in your manifest file

    
    

    Works great for me. :)

提交回复
热议问题