简体   繁体   中英

Displaying an image from the internet with android

I am writing on an android app, and my current task is to load an image from a URL and display it in an ImageView. What i did so far: I managed to download the image and save it as a bitmap. Now when i want to add it to an intent via

intentRecord.putExtra("Data",(DownloadDataImage) result);

where result is my bitmap image, i get an error because a bitmap is not serializable, and .putExtra() requires a serializable input. Do you guys know any workaround for me? I don't know how to circumvent my problem in an appropriate way.

Is there a way of adding an image to an imageView without using a Bitmap, and instead using another serializable type? Or is there a smooth way of making my bitmap serializable? I know this is possible, but i am not quite sure how to do this.

Thx a lot for your help!

I suggest you to try picasso to do the hard work of handling/caching images. Once you have the jar in your workspace, you just need one line of code

Picasso.with(context).load(image_url).into(imageView);

Because there is an upper bound to the size of what can be put in Intent extras, you should look into another way to get the image into your ImageView.

At a very high level the steps of this could be:

  • IntentService downloads image and stores it somewhere that's globally accessible (in-memory cache or on disk).
  • After download has completed and service has saved the image somewhere, it sends a broadcast to let BroadcastReceivers in your app know that the image is now available.
  • A BroadcastReceiver in the activity or fragment that is hosting your ImageView would then retrieve the image from the stored location and place it inside the ImageView (if from disk then remember to do this retrieval off the main thread).

As other answerers have mentioned, there are frameworks that do a lot of this boilerplate work. Picasso , as suggested by droidx, is a great solution that's easy to implement and would probably be your best bet.

you can use external library like Universal Image Loader and you won't have to worry about cache management and other things...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM