How to easily load an image from a URL using two lines of code in Kotlin.
As we may know creating our own framework to download images from the web may not be feasible if we are in a time constraint. Picasso is a cool framework by Square that makes our life supper easy by just adding one line of code to our gradle, and one line of code to fetch the image and place it into our image view. Lets get started. First open your build.gradle (module: app) file. Then place the following implementation in our gradle file.
implementation 'com.squareup.picasso:picasso:2.71828'
Make sure to sync your gradle file after inserting this line of code. Now we will write the magic line of code that does the fetching of the image for us. In the case where you wouldn’t be able to use this dependency you would have to write about 70 lines of code to create a similar but smaller framework. This framework has some really cool features which we will not cover today, but it is nice to mention them. This framework can download images and save them to the device, it can cache the images for a specific session, and many more. Today we will only display the image, not download it. Eventually I will do a cache tutorial on android because it is a fun topic. Now lets show you that magic line of code.
Picasso.get().load(imageURL).into(myImageView)
The barebones of this function is as follows
Picasso.get().load(/*Insert image URL as a string*\).into(/*place your ImageView here*\)
Picasso’s api function to fetch a image takes two parameters in total. First you insert your image URL as a string, and then you pass in your ImageView. This is a super simple use case for this framework, but this framework is very powerful. Thank you for reading my tutorial. Stay tuned for more content li ke this.
Under the Hood:
Picasso is written in Java, however Kotlin can use Java frameworks. What we did with Picasso works as follows. Picasso takes the image and converts it into a Bitmap, and than assigns the Bitmap to the ImageView. Picasso uses some more optimization which is way beyond my understanding. For example I had a RecycleView, and the images would only load when they are displayed on the screen. The images array would not load all at once, thus optimizing the UI performance experience.
PS:
Today I wrote a android app that used this framework, and Gson which are both Square API’s. I combined Picasso and Gson in this app, and realized how nice Square’s API’s are. I hope you enjoyed this tutorial. It was fun making it.