QR Codes in Your Mobile Apps, Cross Platform

Abstract cloud computing service background. Technology and data concept. 3D Rendering

QR Codes in 11 lines of code? Easy. Let’s look at how we can leverage some free APIs from Google to get flexible QR codes in your mobile apps.

Let’s start off with the final product — a function we can call to create a Ti.UI.ImageView with a QR code in it:

See? 11 lines of code (excluding the comments at the top).

Now let’s run through what the lines do.

  • Line 1 and 11 make a function; we want to use reuse this code in multiple places in our code, so we stick it in a function.
  • Line 2 creates the image URL that we will load. It is something particular to Google’s Charts API. In particular, we set “chs” to the size of our QR code, and “chl” to the text we want encoded. Note how we encodeURI the text so that we have a valid URL!
  • Line 3 uses some JavaScript trickery to split the “300×300” string in to the width and height. We’ll use this to explicitly size our ImageView.
  • Lines 4 through 7 ensure that our ImageView will size properly on Android by adding the “dp” (density independent pixels) unit on to our width and height.
  • Lines 8 through 10 make our ImageView and return it! We leverage the ImageView’s capability to download remote images to keep our code extraordinarily simple.

So how do you use it in your code? That’s also very simple. Here’s an example that you could drop in an app.js, along with the above createQRCodeImageView function:

Now you’re off and running with QR codes! But I don’t want to leave you with just that. I want to leave you with a challenge, too.

The “hardest part” of the above code was coming up with our URL and sticking it in an image view — and that wasn’t very hard at all. But what if you want to cache the QR code locally so that the user can see it even when they aren’t online? What’s your first guess at how you’d implement this? Use the Ti.Network.HTTPClient? That would work. But there is a much easier way. Check out the below code sample; I want you to carefully read through it to understand how it works. You can do it!

Can you think of a better or simpler way? Hit me up in the comments, because I would love to know! Or  [shameless plug] come to CODESTRONG and talk to me about your code in person [/shameless plug].


Comments are closed.