Setting asynchronously an image downloaded from a url with Picasso in an android Preference.

Photo by Julie Kwak on Unsplash

Synchronous requests are easy to read and debug. The thread freezes until you get a response back. You handle errors and that’s it.

The thing is that we want users to continue interacting with the application while the program waits to get a response back. The error handling and debugging becomes a bit more complicated.

In our case we can leave all this handling to Picasso, a powerful image downloading and caching library for Android.

Suppose that we have a custom preference category for the settings of my application with various sub sections.

Now as we can see above, the custom preference uses a custom layout that handles how the image should be in terms of sizes and margins with the ImageView. Its is important to match the android id of the custom layout.

Don’t forget the dependencies

Inside your build.gradle file add the following line, gradle sync and verify that you build correctly and that you can import Picasso.

implementation “com.squareup.picasso:picasso:(latest version here)”

The current version as of November 2020 is : 2.71828

Now inside the kotlin file that controls this fragment we can use Picasso to fill this image from a url we have.

Finally we could make this picture round so it can be displayed nice and beautifully. Note that this works well for square images so you can adjust this corner radius according to your needs.

Awesome, we just updated our settings icon!

--

--

Leonidas Boutsikaris

Software Engineer, writing code and blogging about it. Found something interesting? Buy me a coffee! https://ko-fi.com/leobouts