In the section, we will use generate the QR code using a web request. You can use any other web service of your choice for your project, but in this tutorial we will use a free API from QuickChart .
Because the app will be making requests to the internet, let's add the internet permission to the app's manifest. In your AndroidManifest.xml, add the permission (outside the application tag as follows:
For the network requests, we will use the Volley library . Add the library as a dependency in your module level build.gradle file:
Next, we will have out network requests handled by a singleton helper class. Create a new file named HttpHelper.java and in it, add the singleton class:
We created the HttpHelper class and set it up as a singleton that has a RequestQueue instance (class from Volley library) ready for use in making requests.
For our app, the max width or height of our QR codes will be 1080 pixels. So let's represent that with a final variable MAX_SIZE:
The work of requesting a QR code image will be done by the downloadImage() method. Because the method will trigger a network request and we will not know the exact time or duration of the request, we will use a interface as a callback to hold a reference to a method that will be called when the request is completed and a QR code image is available for the app to display. Create a new file named DownloadImageCallback.java and in it add the interface:
The interface uses the ImageSize enum which we already implemented in a previous section. The downloadImage() method itself will be as follows:
Note that the ImageRequest will automatically resize images that are larger that the specified max dimension (1080 pixels in our case). In order to preserve the aspect ratio of the image, we are using the CENTER_INSIDE scale type. Volley enqueues requests and sends them on a background thread, so we do not have to worry about network requests on the main thread of the application.
The error handler for request uses a string resource named check_connection. In your strings.xml add:
Another thing we are missing it the urlEncode() method of the Util class. The method will do exactly what the name implies - it will encode the argument such that it can be used in urls and then return the encoded value as a string:
That is all for this helper class (View the full code here ). In the next section we will use it to seamlessly get the QR code images for our app.