Connect native Android app to Watson Sentiment Analysis in under 10 minutes

By: Marek Sadowski

Connect native Android app to Watson Sentiment Analysis in under 10 minutes

This blog post describes how you can add Watson’s cognitive service to an Android app in about 10 minutes. This app was demonstrated at JavaOne 2016 as shown in the following video:

 

 

OK, let’s get going!

Prerequisites

Overview of steps

Below is an overview of the steps:

  1. Create a typical Android application in Java

  2. Add the Watson lib: Watson-Developer-Cloud SDK for Java

  3. Instantiate the Bluemix Watson service and get the key token to it

  4. Add some code in your Android app to invoke the cognitive service

  5. Quick test of the app.

Step 1: Create a typical Android application in Java.

You’ll build a simple application with a submit button, an editable text field, and an output field.

Idea: Create the user interface first; it’s a simple single view application with a GUI that includes a text field, a label, and a button. When the user presses the button, the text in the text field is sent to the Watson service that will be implemented in the next steps; Watson analyzes it and returns a JSON result that is shown in the output field.

For now, you would take the text in the text field and simply echo it in the label field when the button is pressed.

UI layout: The video below shows the steps, followed by a more detailed explanation:

 

Android

To begin, launch the Android Studio. You start with the New Project option. Choose the app name, and enter your company domain name. Choose the environment the app will run on (I selected API 22 – Android 5.1 Lollipop). I added an empty activity and kept the defaults for the activity. The remaining steps are as follows:

  • Wait until Gradle builds the environment. When it is done, select directory res / layout and double click on activity_main.xml

  • When the UI designer appears you might want to select the TextView widget on the layout designer; the selected text shows “Hello World!”

  • Let’s add Plain TextView to enter text to be analyzed by Watson Sentiment Analysis service. Double click on the widget to add a value (any test text will do).

  • And also let’s add the Button to fire an action. Double click on the widget to add a value as the button label.

add the Button to fire an action

UI wiring: Get back to the code by selecting java, your appName (with your company domain name) and MainActivity. You need to double click the activity. Then add these parameters just after the import section in the class definition: textField, editField, button. It should generate the required imports:

import android.widget.Button;<br>
import android.widget.EditText;<br>
import android.widget.TextView;<p></p>
<p>public class MainActivity extends AppCompatActivity {</p>
<p>    TextView textView;<br>
    EditText editText;<br>
    Button button;<br>
    String sentiment;</pre><br>
Then you need to initialize the view and the UI parameters:<br>
[code]@Override<br>
    protected void onCreate(Bundle savedInstanceState) {<br>
        super.onCreate(savedInstanceState);<br>
        setContentView(R.layout.activity_main);</p>
<p>        //initialize UI parameters<br>
        textView = (TextView) findViewById(R.id.textView);<br>
        editText = (EditText) findViewById(R.id.editText);<br>
        button = (Button) findViewById(R.id.button);</p>

Then fire an action (through OnClickListener) when the button is pressed:

@Override<br>
    protected void onCreate(Bundle savedInstanceState) {<br>
        super.onCreate(savedInstanceState);<br>
        setContentView(R.layout.activity_main);<p></p>
<p>        //initialize UI parameters<br>
        textView = (TextView) findViewById(R.id.textView);<br>
        editText = (EditText) findViewById(R.id.editText);<br>
        button = (Button) findViewById(R.id.button);</p>
<p>        //fire action when button is pressed<br>
        button.setOnClickListener(new View.OnClickListener() {<br>
            @Override<br>
            public void onClick(View v) {<br>
                System.out.println("Logging to the console that the button pressed for the text : " + editText.getText());<br>
                textView.setText("Displaying at UI the sentiment to be checked for : " + editText.getText());</p>
<p>                AskWatsonTask task = new AskWatsonTask();<br>
                task.execute(new String[]{});<br>
            }</p>
<p>        });<br>
    }</p>

Now we need to add the AskWatson task that manages the thread for listener. The text needs to be added just before the onCreate method:

private class AskWatsonTask extends AsyncTask&lt;String, Void, String&gt; {<br>
        @Override<br>
        protected String doInBackground(String... textsToAnalyse) {<p></p>
<p>            System.out.println(editText.getText());</p>
<p>            runOnUiThread(new Runnable() {<br>
                @Override<br>
                public void run() {<br>
                    textView.setText("what is happening inside a thread - we are running Watson AlchemyAPI");<br>
                }<br>
            });<br>
            sentiment = "Test sentiment";<br>
            System.out.println(sentiment);</p>
<p>            //passing the result to be displayed at UI in the main tread<br>
            return sentiment;<br>
        }</p>
<p>        //setting the value of UI outside of the thread<br>
        @Override<br>
        protected void onPostExecute(String result) {<br>
            textView.setText("The message's sentiment is: " + result);<br>
        }<br>
    }</p>
the results from Watson

The selected task will call and fetch the results from Watson (to be implemented in the next sections).

 

Now we are ready to run the simulator - press the green "PLAY" arrow next to the "APP". Building the app and launching the simulator (or connecting to the device) takes a few moments:

PLAY

If you click the Analyze! button, you should be able to see the result at the TextView field. You should also see some output in the console debug.

Get Cognitive!

The video below shows all the steps followed by a more detailed explanation.

Step 2: Add the Watson lib: Watson-Developer-Cloud SDK for Java

Check the detailed installation steps in the Watson Developer Cloud SDK for Java on GitHub.

Alternatively, download the Java library for the SDK (jar) and place it in the lib folder to get in included for the environment. Specifically, put the downloaded jar file in the libs folder under the app root directory apps/libs as follows:

Add the Watson lib: Watson-Developer-Cloud SDK for Java

You should be able to see the app in the libs folder in the projects view in the Android Studio. Then double click on the jar to add it to the [app] as the library. Finally we are able to import those Watson libraries:

//adding Watson Developer Cloud SDK for Java:<br>
import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage;<br>
import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentSentiment;

Now we need to allow to call Watson service from our app. Double click /app/manifest/AndroidManifest.xml in the view Android and add the following two lines:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

For reference, the following is the entire file content:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ibm.sentimentsensitiveapp">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 3: Instantiate the Bluemix Watson service and get the key token to it.

Next you'll connect your code to the Watson AlchemyAPI service. From the IBM Bluemix catalog, click Watson > AlchemyAPI > Create. Be sure to use a static API key as shown in the following image:

Watson AlchemyAPI service

Bluemix provides your credentials in JSON format. The JSON snippet above lists credentials, such as the API token, or a key/secret pair, and connection information for the service.

Step 4: Add some code in your Android app to invoke the cognitive service.

Next you'll add Watson credentials to the code and initialize the Watson Developer Cloud SDK for Java service. We are going to leverage Sentiment Analysis from Watson AlchemyAPI service. First we need to import the required classes:

import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage;<br>
import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentSentiment;<br>

Then we can expand the AskWatsonTask private class. First we need to instantiate the AlchemyApi service:

AlchemyLanguage service = new AlchemyLanguage();<br>
            service.setApiKey("");<p></p>
<p>            Map&lt;String, Object&gt; params = new HashMap&lt;String, Object&gt;();<br>
            params.put(AlchemyLanguage.TEXT, editText.getText());<br>
            DocumentSentiment sentiment = service.getSentiment(params).execute();<br>
            System.out.println(sentiment);</p>
<p>            //passing the result to be displayed at UI in the main tread<br>
            return sentiment.getSentiment().getType().name();</p>

Step 5: Quick test of the app

Do a quick test of your app:

Quick test of the app

When we run the app in the simulator, and hit the Analyze button, in the UI we see POSITIVE or NEUTRAL or NEGATIVE sentiment of the message. More information about the weight of the result (positive or negative) is shown in the returned JSON from Watson service and printed on the console. An example JSON sentiment result for the input "This is not a nice car" is shown below:

{<br>
   "docSentiment": {<br>
     "score": -0.42344,<br>
     "type": "negative"<br>
   },<br>
   "language": "english",<br>
   "totalTransactions": 1<br>
}

Please follow me on Twitter: @blumareks, and check my blog on blumareks.blogspot.com. For reference, please see this Gist on GitHub for a full listing of the application above.

Be the first to hear about news, product updates, and innovation from IBM Cloud