How to Build an Android App with JavaScript

Build an Android App with JavaScript for Generating QR Codes

We are back with yet another Android app demo. This time, we take a different approach to building an Android app with JavaScript.

Being the de-facto programming language for the web, JavaScript has enjoyed tremendous growth over the years, especially in frontend browser-based applications. Thanks to the advances in runtime environments and the tooling, it is now possible to take JavaScript off the browser and use it in other ways. In this blog post, we show you how to build an Android app using JavaScript and related web technologies, without using any native Java or Kotlin based environments. We also show you how to integrate an API with such Android applications by leveraging the power of the RapidAPI‘s API marketplace.

Can we use JavaScript for Android?

Yes, of course!

The Android ecosystem supports the concept of hybrid apps, which is a wrapper over the native platform. It mimics the UI, UX, and all kinds of hardware and network interactions, just like how you would use a native Android app.

Many frameworks offer a hybrid wrapper for Android. The Ionic framework is the most popular among the developer community. It leverages the Cordova WebView plugin, which is a browser like skin over the native Android UI. 

Using the Ionic framework for Building Android Apps with Javascript

The ionic framework works with Angular, React as well as vanilla JavaScript or Vue, to bind the application. Ionic 5 is the latest version of the framework. The support for React, JavaScript, and Vue was added in version 4. However, JavaScript and Vue support is still not stable enough to build production-grade apps. Therefore, as of this writing, it is recommended to use Angular with Ionic 5.

Using the TypeScript language, a superset of JavaScript, you can build an Ionic application on top of Angular, which runs as a hybrid Android app using the WebView plugin.

The Ionic framework acts as the glue between the Android platform, Angular, and Cordova. The resulting hybrid app feels just as good as a native app. A regular user would never be able to make out the difference.

The only downside is these apps is that they are not performant like native apps. Moreover, these apps cannot command fine-grained control over the underlying hardware in case of a need for hardware boosted performance.

Building the UI Layer for Ionic Hybrid App

The Ionic framework offers a set of UI components that you can use to build the app UI.

Like you use HTML tags to build the browser UI, Ionic offers high-level custom tags to build the app’s UI elements.

Here is how you can piece together an app screen to display a piece of small information on a card.

Using the <ion-card> tag, you can build this screen as follows.

<ion-content fullscreen>
      <ion-card>
        <img src="./madison.jpg" />
        <ion-card-header>
          <ion-card-subtitle>Destination</ion-card-subtitle>
          <ion-card-title>Madison, WI</ion-card-title>
        </ion-card-header>
        <ion-card-content>
          Founded in 1829 on an isthmus between Lake Monona and Lake Mendota, Madison was named the capital of the Wisconsin Territory in 1836.
        </ion-card-content>
      </ion-card>
    </ion-content>

In this way, Ionic provides a complete library of UI specific custom elements to build UI screens for apps.

Making API Calls from Ionic Hybrid App

If you are using Angular as the base framework, then making an API call is easy.

Angular provides an HTTP client library for TypeScript that leverages the HTTPClient class.

This class provides all the HTTP methods, including the most common ones, post() and get() to invoke API requests from an URL. Here is how you can define a module to make a quick API call using HTTPClient and a few helper classes.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class HTTPService {
  // inject the HttpClient in the constructor
  constructor(private http:HttpClient) { }
  get(): Observable<any> {
    
    let getUrl = "https://http://example.com/;
       
    return this.http.get(getUrl,{responseType:'blob'});
  }
}

By importing this module in an Angular app, you can call the function get( ). It will return the HTML body of the example.com domain as a text blob.

How to Build an Android App with JavaScript (for QR Code Generation)

QR codes get a lot of love from people from around the world. Everybody loves to scan a QR code. Companies and brands want to use them to lead customers to their website URLs.

So how about building an Android app that lets you instantly generate a QR code from an URL. Before you even wonder about the nitty-gritty details of generating the QR code, let us remind you that the RapidAPI’s API marketplace has many APIs to help you with that.

Choosing a QR Code Generation API

Head over to the RapidAPI homepage to search for QR code APIs.

You can find a lot of QR code APIs listed on the marketplace.

There are wide varieties of API choices to generate customized QR codes, with images, logos, and color combinations along with various options to access the generated code.

Let’s pick a no-frills QR code generator for the Android app that we want to build.

We have done a random pick to choose the QRickit QR Code QReator API. It is a simple, easy to use API without any customization options.

Follow the steps below to get started with this API.

How to Get Access to the API

1. Sign up for RapidAPI Account

To access any API, you’ll first have to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.

2. Access the QRickit QR Code QReator API

Once signed in, log in to your RapidAPI account and visit the API console here.

3. Subscribe to the QRickit API

Once inside the API console, click on the “Pricing” tab to access the pricing plan.

The QRickit QR Code QReator API offers a freemium plan that lets you make 100 API calls in a month.

Subscribe to this plan, and you are all set to try it out.

4. Test the QRickit API

If you go back to the “Endpoints” tab, you can access the API endpoints and the parameters.

Key in the domain name “example.com” in the text box next to the parameter  ‘d’. Trigger the API. If you see a status code of 200, then the API call has succeeded.

The actual QR code image is sent as a blob response by the API, which may not be visible on the browser. However, when you build the Android app, you will capture it and display it as an image.

Let’s create the app with Ionic Framework

We will now write the code for the Android app. To build this app using the Ionic framework, you need to set up some tooling.

First up, here are a few prerequisites for platforms and SDKs that must be satisfied before proceeding further.

Prerequisites

    1. Install Android Studio: This is the Android development environment. You must have the Android Studio version 3.0 or above, installed on your development computer.
    2. Install Java SDK: All Android applications leverage the Java platform. You need to install the JDK from the official Oracle website.
    3. Install Android SDK: This is the Android platform SDK. You must have the latest Android SDK (preferably Android 10.0) installed through the Android Studio.
    4. Install Node.js and NPM: NPM is the package management tool for all Angular and Ionic packages as well as the TypeScript libraries. It is available as part of the Node.js package. You can install Node.js from the official page.
    5. Install Angular: Follow this official guide to set up your local Angular environment.
    6. Install Ionic: Install the ionic CLI from this official Ionic docs. Only follow the section until the installation of the Ionic CLI. 

Note: The code presented in this post has been tested with the following versions of the platforms/SDKs on Windows 10.

Android Studio: 3.5.3

Java 1.8.0.241

Android SDK: Android 10.0

Node.js/NPM: 10.16.3/6.13.7

Angular CLI: 9.1.11

Ionic CLI: 5.4.16

You also need to make sure that the system paths for Android SDK, Java, Node, NPM, Angular CLI, and Ionic CLI are correctly set to invoke them directly.

Let’s start the development now. Follow along with the steps below to set up a new Ionic project and build the Android app’s code.

Before starting, make sure that you have a command-line terminal running and a code editor open.

Step 1: Create a new Ionic project

On the terminal, create a new project folder and then, while inside the folder, create a new Ionic project using the Ionic CLI.

ionic start qrcode blank

This will create a new blank project called “qrcode.” It automatically creates the project main folder named “qrcode” and the subfolders within.

Step 2: Add a new HTTP service to the project

For triggering the API calls from the app to the QRickit API, we define a new service. Invoke the following command using the Ionic CLI.

ionic generate service HTTP

A service is an add-on module, used as a library across the code. It performs a well-defined responsibility. In this case, it is the invocation API calls.  You will define the logic inside this module in a little while.

Step 3: Add the UI and interaction code

This app only has one screen. It displays a text box to accept the domain name and a submit button to trigger QRickit API call. Below the button is a display area that shows the generated QR code.

Open the file home.page.html under qrcode/src/app/home/ to define the UI as follows. You can overwrite the default content generated as part of the project creation.

<ion-header [translucent]="true" color="primary">
  <ion-toolbar  color="primary">
    <ion-title style="text-align: center;">
      QR Code Generator
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true"  color="primary">
  <form name="inputForm"  id="inputForm"  (ngSubmit)="getQRCode()" >
    <ion-grid>
      <ion-row color="primary" justify-content-center>
        <ion-col align-self-center size-md="6" size-lg="5" size-xs="12">
          <div padding>
            <ion-item color="primary">
               <ion-label>Enter the URL </ion-label>
            </ion-item>

            <ion-item>
              <ion-input name="apiurl"   id="urlString" placeholder="URL" [(ngModel)]="urlString" required></ion-input>
            </ion-item>
          </div>
          <div padding>
            <ion-button size="large" type="submit"  expand="block"  >Get QR code</ion-button>
          </div>
        </ion-col>
      </ion-row>
    </ion-grid>
  </form>

  <div id="resultDiv" *ngIf="showResult" style="height: 50%;">   
    <ion-card id="resultCard" style="text-align:center;color:white;font-weight: bold;" color="success">
      <ion-card-header>
        <ion-card-subtitle id="resultUrl">{{resultUrlString}}</ion-card-subtitle>
        <ion-card-title id="resultTitle">QR Code</ion-card-title>           
      </ion-card-header>  
      <ion-card-content text-center>
        <ion-row>
          <div class="loading" *ngIf="loading" id="loader" style="position:relative;left:45%;"></div>   
        </ion-row>
        <img style="margin-left:5%;width:50%" #qrCodeImage />
      </ion-card-content>
    </ion-card>
  </div>
  <div id="errorDiv" *ngIf="showError">   
    <ion-card id="errorCard" style="text-align:center;color:white;font-weight: bold;" color="warning">
      <ion-card-header>     
        <ion-card-title id="resultTitle">ERROR!</ion-card-title>  
        <ion-card-subtitle id="resultUrl">{{errorMessage}}</ion-card-subtitle>         
      </ion-card-header>  
    </ion-card>
  </div>
</ion-content>

<ion-header> and <ion-content> defines the top level wrappers for housing the UI elements.

The UI is structured in a typical HTML fashion using <div> elements containing both Ionic specific custom elements, as well as standard HTML elements. This includes <ion-card>, <ion-item>, <ion-label>, <ion-button>, along with <form> and <img> tags.

Now open the file home.page.scss and replace the default content with this.

#container {
  text-align: center;

  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

#container strong {
  font-size: 20px;
  line-height: 26px;
}

#container p {
  font-size: 16px;
  line-height: 22px;

  color: #8c8c8c;

  margin: 0;
}

#container a {
  text-decoration: none;
}

.loading {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: 3px solid rgba(255,255,255,.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
  -webkit-animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { -webkit-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
  to { -webkit-transform: rotate(360deg); }
}

This is the standard CSS stuff that you define to style the UI components. The most notable thing here is .loading class. It defines the loading animation to be displayed while waiting for the API response.

Now open the file home.page.ts and replace the default content as follows.

import { Component, ViewChild , ElementRef} from '@angular/core';
import { HTTPService } from '../http.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  loading:boolean;
  showResult:boolean;
  showError:boolean;
  imageUrl="";
  errorMessage="";
  urlString="";
  resultUrlString="";

  @ViewChild('qrCodeImage') image: ElementRef
  constructor(public  httpService : HTTPService ) {
    this.loading = false;
    this.showResult = false;
    this.showError = false;
  }
  // This validates the url string to be in proper format
  validURL(urlStr) {
    console.log("validating url")
    var regex = /^(?:(?!(?:10|127)(?:.d{1,3}){3})(?!(?:169.254|192.168)(?:.d{1,3}){2})(?!172.(?:1[6-9]|2d|3[0-1])(?:.d{1,3}){2})(?:[1-9]d?|1dd|2[01]d|22[0-3])(?:.(?:1?d{1,2}|2[0-4]d|25[0-5])){2}(?:.(?:[1-9]d?|1dd|2[0-4]d|25[0-4]))|(?:(?:[a-zu00a1-uffff0-9]-*)*[a-zu00a1-uffff0-9]+)(?:.(?:[a-zu00a1-uffff0-9]-*)*[a-zu00a1-uffff0-9]+)*(?:.(?:[a-zu00a1-uffff]{2,})))(?::d{2,5})?(?:/S*)?$/;
    console.log(regex.test(urlStr))
    if(regex.test(urlStr)){
      return true;
    } else{
      return false;
    }
  }

  getQRCode(){
    this.showError=false;
    this.showResult=false;
    this.loading = true;
    if(this.validURL(this.urlString)){
      console.log("valid url")
      // saving the string for result display
      this.resultUrlString =this.urlString;
      // call the http service which in turn calls the RapidAPI
      this.httpService.get(this.urlString).subscribe(response=>{
        // on receiving response disable the loading 
        this.loading=false;
        // clear the input string
        this.urlString="";
        // create a local url for the recieved image and assign it to the source of image element for display
        this.image.nativeElement.src = window.URL.createObjectURL(response);
      });
      // display the result url
      this.showResult=true;
    }else {
      // on error disable the loading symbol
      this.loading = false;
      // set the error message
      this.errorMessage = "Please enter valid url in the format www.yourdomain.com";
      // clear input string
      this.urlString="";
      // display the error message
      this.showError = true;
    }
    
  }
}

This code is in TypeScript.  It defines the business logic for the UI. The only interaction point for this app is the button press to invoke the QRcikit API and display the generated QR code.

The getQRCode( ) function handles this. You can follow the comments in the code to understand the flow.

This also uses the HTTP service for API invocation. You will tackle this function in the next step.

Step 4: Add the code for HTTP service

Open the file http.service.ts under /qrcode/src/app path and replace the existing content with this code.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class HTTPService {
  // inject the HttpClient in the constructor
  constructor(private http:HttpClient) { }
  get(url:String): Observable<any> {
    
    let getUrl = "https://qrickit-qr-code-qreator.p.rapidapi.com/api/qrickit.php?d="+url;
    // create headers and set host and api key (obtained from RapidApi)
    const header = new HttpHeaders({'x-rapidapi-host':'qrickit-qr-code-qreator.p.rapidapi.com',
                  'x-rapidapi-key':'<YOUR_RAPIDAPI_KEY>'});
    // result is in the form of image in blob
    return this.http.get(getUrl,{headers:header,responseType:'blob'});
  }
}

Before saving the file, make sure to replace the placeholder <YOUR_RAPIDAPI_KEY> with the actual key generated for you during account creation.

This service defines a get( ) call that wraps the HTTP GET method for involving the QRickit API. The API response is returned as a blob, which is the base64 image data.

Step 5: Registering the HTTP service with app

You have defined the HTTP service, but it uses the Angular HTTPClient module, which needs to be imported to the project so that other modules can use it.

Open the file app.module.ts file under qrcode/app. Add the following import statement below all the other import statements.

Import . . . . 
import { HttpClientModule } from '@angular/common/http';

Further, add the HttpClientModule for imports under the @NgModule block.

imports: [BrowserModule, HttpClientModule, IonicModule.forRoot(), AppRoutingModule],

With this step, coding is complete.

Step 6: Generate Android artifacts

To generate an Android app from this Ionic project, you will need to add Android specific artifacts.

First, you must ensure that the build environment for Android is correctly set up.

Now open the config.xml file under qrcode path and change the value of the <name> tag to QRCodeGen. The content of this tag will be the name of the app that installs on Android phone.

After that, switch to the terminal where you created the Ionic project. Make sure that you are under the “qrcode” path and issue the following commands.

1. Add the Android platform to Ionic project.

ionic cordova platform add android

2. Build the Android app

ionic cordova build android

Note: These commands will take some time to execute, anywhere between 5 to 10 minutes. If you face any errors due to the unavailability of dependencies, please follow the error messages to install the dependencies and run the command again.

At the end of the build step, you will see the new Android .apk file under the qrcode/platforms/android/app/build/outputs/apk/debug path.

Step 7: Test the Android app

To test the app, you can use the Android emulator that comes by default with the Android Studio.

Launch the Android studio. On being prompted by the welcome screen, choose the option for opening an existing project, and navigate to the “qrcode” project folder. This will open the Android Studio IDE and show the “qrcode” folder structure.

Note: The Android Studio is used to launch the emulator only. We are not going to use it to build the app.

Now launch the AVD manager from the top toolbar, and you will see the list of available virtual devices.

Double click on the virtual device to launch it. It will take a few minutes to start and display the Android screen. 

Now drag and drop the .apk file on the emulator window. This action will install the app on the emulator device. It will create an app icon with the name QRCodeGen, as per the name you defined in the config.xml file.

Once installed, navigate to the app, launch it, and you are ready to test it.

Voila!

You have just created an Android app with JavaScript without using any of the native Android development tools.

What’s Next?

If you are a web developer, you will be most familiar with HTML CSS and JavaScript instead of Java or Kotlin. Hence, this approach is the best way to build an Android app without upskilling yourself.

You should now have a good idea about how to build an Android app with Ionic.  It is a reliable framework, and with a reliable API from the RapidAPI marketplace, you can do wonders with hybrid Android apps.

So what do you want to build?

Share your thoughts and queries in the comments below. We will be back soon with yet another exciting demo around Android.

How to build Android apps with JavaScript?

The preferred development environment for Android app is Kotlin or Java, hence there is no direct way of building an Android app using JavaScript. However, with the help of a framework, it is possible to add a wrapper over the native Android interface. The Ionic framework is one of the oldest and the most popular framework that leverages several web frameworks to provide that wrapper. Apart from supporting vanilla JavaScript, which is still in beta, you can use Ionic with Angular and React to built a hybrid wrapper over Android.

How to generate a QR code?

QR codes can be used to encode useful information ranging from website URLs, contact information as well as other information. The ideal way to generate a QR code is through an API. You can search the RapidAPI catalog to choose one among the many QR code generation APIs.

Is there any API to generate QR code?

Yes. You can generate any QR code representing an URL, of arbitrary data using a QR code generation API. The generated QR code is available through an image that is returned as part of the API response. You can search the RapidAPI catalog to choose from many QR code generation APIs which provide custom options for decorating the QR code images as well as multiple formats to return the generated QR code image.

5 / 5 ( 1 vote )
Shyam Purkayastha

Shyam is the Founder of Radiostud.io, a content-lead innovation studio, focusing on showcasing use cases of emerging technologies. He's an entrepreneur, a technology evangelist, author, and mentor with a deep passion for nurturing ideas and building things around emerging and futuristic trends in Computing, Information Technology, and Telecommunications. GitHub | LinkedIn

Share
Published by

Recent Posts

How to use WordPress with React (WordPress React API Tutorial)

WordPress WordPress claims to be, "the world’s most popular website builder" based on the statistic…

1 week ago

How to use an E-mail API with JavaScript

Introduction This tutorial will show you how to use JavaScript to call an API to…

1 week ago

How to Document your API

Documentation is an essential part of any API, and this is what we're going to…

2 weeks ago

How to use the Google Play Store API to Search App Details

Modern mobile phones are replacing many different devices and services. And the bigger part of…

2 weeks ago

The 10 Chrome Flags That Can Transform Your Browsing Experience

Being one of the most popular web browsers out there, Google Chrome has a reputation…

3 weeks ago

How to use the Google Translate API with Ruby on Rails

Google, mostly known for its search engine and extremely popular email service, Gmail, also provides…

3 weeks ago