Taxonomy Icon

Mobile Development

IBM Watson may be best known for competing on the US quiz show Jeopardy, but the technology goes far beyond simple questions and answers. Watson is an entirely new form of computing, one that promises to discover hitherto undiscovered insights based on the wealth of data all around us. While traditional computer models have relied on rigid mathematic principles, utilizing software built upon rules and logic, Watson instead relies on what IBM is calling “cognitive computing”. IBM Watson has multiple services that includes Assistant, Discovery, Personality Insights and many more.

The Watson team also provides multiple software development kits (SDKs) to help developers use Watson with various programming languages. The watson-developer-cloud GitHub organization has a full listing of available SDKs.

Learning Objectives

After completing this guide the reader will know how to:

  • Download and Install the Watson Android SDK
  • Use Android Studio with the Watson Android SDK
  • Use Watson services through their service credentials and APIs in Android Studio
  • Build and run a sample Android application that uses Watson

Prerequisites

To follow this How-to guide, you need to have:

Estimated time

To complete the how-to should take about one hour. Thirty minutes for the prerequisites and another thirty minutes for the guide.

Steps

Note: This how-to was tested with Android Studio 3.0.1, Watson Android SDK v0.4.3, and macOS High Sierra

Download the Watson Android SDK

Navigate to the Watson Android SDK on Github and click the Clone or Download button to download the repository as a ZIP file.

Optionally, we encourage the reader to check out the watson-developer-cloud GitHub organization that the Watson team maintains to see all other available SDKs.

Create a new Watson Android SDK project in Android Studio

We’ll now use the example folder in the Watson Android SDK as a starting base.

  • Unzip the newly downloaded ZIP file (probably named android-sdk.zip) into a new workspace folder.
  • Launch Android Studio.
  • Click File > Open in the menu bar and provide the example folder of the un-zipped file.
  • Android Studio will now build the project using Gradle

Note: If you see a Install missing platform(s) and sync project error or Install Build-Tools 26.0.1 and sync project error, then click the hyperlink provided to install the missing platform or tools. Once installed the build should restart and complete successfully.

Exploring the sample application

Let’s now take a look at the sample application provided in the SDK. Specifically, let’s open the file MainActivity.java, which is located at example > java > com.ibm.watson.developer_cloud.android.myapplication > MainActivity.

Here you will see that there are plenty of libraries already imported for the sample application. To use other available libraries, you can import them as shown below:

By expanding the import section at the top of the file (clicking on import ...) you’ll be able to see the various imports used in MainActivity.java. Note the ones used by the watson_developer_cloud package, the Watson Android SDK. To quickly see a complete list of other Watson services you can use, type in import com.ibm.watson.developer_cloud. and let the auto-complete show you what is available.

Now let’s check out activity_main.xml, which is located at example > res > layout > activity_main.xml. This XML file contains the layout for MainActivity.java. By double-clicking activity_main.xml Android Studio will automatically generate a sample design of the activity for the application. You can also edit this design by clicking Text at the bottom left corner of the tab to see the XML written.

Lastly, let’s check out credentials.xml, which is located at example > res > values > credentials.xml. This XML file contains a template for providing the credentials for the various Watson services that are used by the application. In this case, there are three different Watson Services used; Watson Language Translator, Speech to text, Text to speech. Each value in the XML file contains a resource name that can then be referenced from MainActivity.java.

Adding service credentials to credentials.xml

We now copy and paste the credentials for each Watson service to credentials.xml. Refer back to the Prerequisites section for instructions on how to create specific Watson services.

To find the service credential value, log into IBM Cloud and find the service in your dashboard, once selected go to the Service Credentials tab. The image below is the Service Credentials tab for a Language Translator service.

Copy the url, username and password for each service and paste them in into credentials.xml in Android Studio as shown below. Do the same for other services as well.

Build and run the application

Build the application

After providing the credentials for all three Watson services (Language Translator, Speech to Text, Text to Speech) we can now build and run the project. We can either run the application via a connected device or build the APK first and transfer it to a mobile phone to be installed manually. Let’s look at both methods.

Transfer the application to a connected device

Running an Android project on a connected device is an efficient way of debugging projects. It requires the relevant drivers to be installed on both the mobile device and Android Studio. It also requires the user to enable developer mode on your mobile device.

We must first download and install Google USB Driver on Android Studio. Note, that if you are developing on macOS or Linux then you do not need to install the USB driver, instead refer to Using Hardware Devices.

In some cases, additional drivers are needed. When creating this guide, which was tested on Samsung Galaxy S8+ running Android version 7.0, we had to install USB drivers for Samsung on Windows.

Finally, the last step we need to complete to use our device as a connected debugging device is to enable USB debugging. To do so, we need to enable “Developer Mode”. We do this by going into the device’s Settings selecting About Phone, then Software Information, and tapping Build number seven (7) times. Now go to Settings and a new menu, Developer Options will appear, enable USB Debugging to continue.

Now we’re all set for running and debugging on your connected device. Simply click the Play button on the menu bar of Android Studio, shown below in a screenshot:

You should see your connected device in the Select Deployment Target dialog as shown below.

Click OK and the project will start building and run on the connected device.

Generate and install APK

To install the application as an APK we must first generate the APK. To do so, go to Build and select Build APK. Android Studio will start building the project and generate an APK. After the process is complete, you can go to the APK location by clicking Show in Explorer in the Event Log shown below.

Transfer this APK file on your mobile device by any means you like (E-mail, sd card, Google Drive, etc). Open a file explorer on your mobile navigate to the location of the transferred APK. Open the APK file. Android may promt you to allow installing from an unknown source, confirm this choice and the application will start installing on your phone.

Running application

In the screenshot below a sample text is translated using the Watson Language Translator service. You can choose which language you want to translate your text into.

You can also use the microphone to record your input using the Watson Speech to Text service. To do this, click the microphone button next to the text box, say a few words, and click the button again to stop the recording. You can also click the play button to hear the translated text, which uses the Watson Text to Speech service.

Understanding the back-end and API calls

In this section, we shall see how our input is being translated and how the APIs are being called for translating the text into the selected language. We shall see the case of calling the LanguageTranslator API.

We’ll start by importing the Language Translator class by doing:

import com.ibm.watson.developer_cloud.language_translator.v2.LanguageTranslator;

Now let’s create an instance of this class by doing:

private LanguageTranslator translationService;

Now we need to initialize it with the credentials. Note the use of username, password and endpoint/url:

private LanguageTranslator initLanguageTranslatorService() {
LanguageTranslator service = new LanguageTranslator();
String username = getString(R.string.language_translator_username);
String password = getString(R.string.language_translator_password);
service.setUsernameAndPassword(username, password);
service.setEndPoint(getString(R.string.language_translator_url));
return service;
}

Now we will see what is going on at the back-end of the Translate button. When a user clicks the Translate button, the following function is called:

translate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    new TranslationTask().execute(input.getText().toString());
    }
});

The click event calls the TranslationTask() which is implementing the AsyncTask with the following code:

private class TranslationTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
    showTranslation(translationService.translate(params[0], Language.ENGLISH, selectedTargetLanguage).execute()
        .getFirstTranslation());
    return "Did translate";
    }
}

If you see closely to this background async task, there is an API being called within the function that is setting the text of the translation shown below:

translationService.translate(params[0], Language.ENGLISH, selectedTargetLanguage).execute()
.getFirstTranslation()

This is the call to the Language Translator Service where we are providing 1) the input text, 2) its language of input (default is set to English), and 3) the selected target language.

This Translator API call returns the result of the translation in the string format, which we are providing to the function showTranslation(final string translation) shown below:

private void showTranslation(final String translation) {
runOnUiThread(new Runnable() {
    @Override
    public void run() {
    translatedText.setText(translation);
    }
});
}

As the showTranslation function is on another thread, separate from the Translation API call we have to add runOnUiThread, which puts it in the queue and executes after the Translation API call and sets the returned text of translation.

Other API calls work in a similar fashion. Kindly refer to link provided in the resources for the documentation of the Watson Services and their API References.

Summary

In this guide, we learned how to: get started with the Watson Android SDK, build a sample application using Android Studio and Watson services, and we did a deep dive into the code base. Please refer to the the links provided in the resources to see other SDKs and Watson API references. Thanks for reading!