Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Connect native Android app to Watson Sentiment Analysis in under 10 minutes
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
//adding Watson Developer Cloud SDK for Java:
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText editText;
Button button;
String sentiment;
private class AskWatsonTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... textsToAnalyse) {
runOnUiThread(new Runnable() {
public void run() {
textView.setText("what is happening inside a thread - we are running Watson AlchemyAPI");
AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("<here goes AlchemyAPI key from Bluemix>");
Map<String, Object> params = new HashMap<String, Object>();
params.put(AlchemyLanguage.TEXT, editText.getText());
DocumentSentiment sentiment = service.getSentiment(params).execute();
//passing the result to be displayed at UI in the main tread
return sentiment.getSentiment().getType().name();
//setting the value of UI outside of the thread
protected void onPostExecute(String result) {
textView.setText("The message's sentiment is: " + result);
protected void onCreate(Bundle savedInstanceState) {
//initialize UI parameters
textView = (TextView) findViewById(;
editText = (EditText) findViewById(;
button = (Button) findViewById(;
//fire action when button is pressed
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("Logging to the console that the button pressed for the text : " + editText.getText());
textView.setText("Displaying at UI the sentiment to be checked for : " + editText.getText());
AskWatsonTask task = new AskWatsonTask();
task.execute(new String[]{});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment