I am writing this short article since I had a pretty hard time figuring out on how to do what the title says: fetching an SVG from the web and displaying it in an app.
By default, Android’s ImageView
does not support SVGs (why?). After googling for a while I found a complicated solution for the above problem using Glide with a custom module in combination with AndroidSVG. However, the latter library is quite outdated and caused some - apparently randomly occuring - errors on API level 28. Finally I found Pixplicity/sharp, which seemed to be a light-weight library for almost exactly my purpose with a minimal API. The only thing I needed to add is the ability to fetch the SVG from the web instead of from a local resource. I built a small example as can be seen below.
Code
build.gradle
1 | dependencies { |
MainActivity.java
1 | // ... |
Utils.java
A simple util class with static methods that receive an Android Context. Having a static OkHttpClient
that gets conditionally initialized from within the static methods might arguably not be the best solution, but it works for this example. Alternatives would be to have it being autowired, passed as a parameter or to make Utils
a singleton and the http client a member variable.
1 | public class Utils { |
If you know a simpler solution to load SVGs, please let me know!