How to get image from url website in imageview in android

前端 未结 4 1569
一向
一向 2021-01-12 10:19

I am trying to get image in ImageView from url website but the image not show so, What is the wrong in this code? This is the url of the image.

It is my Main Activi

相关标签:
4条回答
  • 2021-01-12 10:51

    Doing network IO in the main thread is evil. Better to avoid.

    Also - your url resource access is wrong.

    Use something like this instead:

     private Bitmap bmp;
    
       new AsyncTask<Void, Void, Void>() {                  
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    InputStream in = new URL(IMAGE_URL).openStream();
                    bmp = BitmapFactory.decodeStream(in);
                } catch (Exception e) {
                   // log error
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(Void result) {
                if (bmp != null)
                    imageView.setImageBitmap(bmp);
            }
    
       }.execute();
    

    This is the 'old way' of loading url resources into display. Frankly speaking, I have not written such code in a long time. Volley and Picasso simply do it much better than me, including transparent local cache, multiple loader-threads management and enabling effective resize-before-load policies. All but coffee :)

    0 讨论(0)
  • 2021-01-12 10:53

    Your problem is not in code but with the server. Try this sample url and tell me if is it working:

    http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png

    0 讨论(0)
  • 2021-01-12 10:59

    If you're going to be loading multiple images from URL's in your app, it's definitely worth looking into:

    nostra13's "Universal Image Loader"

    It's an awesome library with tons of features to display images from URLs, cast to bitmaps, etc.

    Once you've included the class and declared the imageloader + imageloader configuration, its a simple as this:

    imageLoader.displayImage("http://www.yoursite.com/my_picture.png", imageView);
    

    Where imageView is the imageView you would like the image to appear in.

    0 讨论(0)
  • 2021-01-12 11:15

    Give it a try with Picasso. It should take you almost one full line of code and less than a minute to set it up.

    In your case, that would be:

    Picasso.with(context).load(""http://imageurlgoeshere").into(i);
    
    0 讨论(0)
提交回复
热议问题