Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB) In this exercise, we will create a simple Android application that uses IBM Bluemix Cloudant NoSQL DB. The application will communicate with a Cloudant NoSQL data base and perform read/write operations on it. 1. Open Android Studio, click on File->New ->New Project (you are free to use any application name and company domain)
2. Click on Next, and make sure only Phone an Tablet is checked. Make sure minimum SDK is set to API 19 or greater. 3. Click on Next, and select Empty Activity. 4. Click on Next, and then click on Finish
5. Open app->java->res->layout->activity_main.xml. Then, click on Text
6. Modify the XML file, so that it looks like this: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="-------------------------do NOT CHANGE ANYTHING HERE--------------------------"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="write" android:id="@+id/writebutton" android:layout_alignparenttop="true" android:layout_alignparentstart="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/idedittext" android:layout_below="@+id/writebutton" android:layout_alignparentend="true" android:layout_alignparentstart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="read" android:id="@+id/readbutton" android:layout_below="@+id/idedittext" android:layout_alignparentstart="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/responseedittext" android:layout_below="@+id/readbutton" android:layout_alignparentstart="true" android:layout_alignparentbottom="true" android:layout_alignparentend="true" /> </RelativeLayout> 7. Open app->java->---context----->mainactivity.java
8. Add the following fields to your MainActivity class private String DB_NAME = ""; private String ACCOUNT = ""; private String USERNAME = ""; private String PASSWORD = ""; 9. Add the following methods and classes to your MainActivity class: private void setupwritebutton() Button button = (Button) findviewbyid(r.id.writebutton); button.setonclicklistener(new View.OnClickListener() @Override public void onclick(view view) writebuttonpressed(); ); private void setupreadbutton() Button button = (Button) findviewbyid(r.id.readbutton); button.setonclicklistener(new View.OnClickListener() @Override public void onclick(view view) readbuttonpressed(); ); private void writebuttonpressed() new WriteAsyncTask().execute();
private void readbuttonpressed() EditText idedittext = (EditText) findviewbyid(r.id.idedittext); String id = idedittext.gettext().tostring(); new ReadAsyncTask().execute(id); class WriteAsyncTask extends AsyncTask<Void, Void, User> @Override protected User doinbackground(void... arg0) User user = null; try // Create a new CloudantClient instance for account endpoint <ACCOUNT>.cloudant.com CloudantClient client = ClientBuilder.account(ACCOUNT).username(USERNAME).password(PASSWORD).build(); // Get a Database instance to interact with. Do not create it if it doesn't already exist Database db = client.database(db_name, false); user = new User("RandomFirstName", "RandomLastName", new Date(), 18); db.save(user); catch (Exception e) e.printstacktrace(); return user; @Override protected void onpostexecute(user user) super.onpostexecute(user); EditText responseedittext = (EditText) findviewbyid(r.id.responseedittext); responseedittext.settext("user created:\nid:" + user.getid()); class ReadAsyncTask extends AsyncTask<String, Void, User> @Override protected User doinbackground(string... arg0) User user = null; try String id = arg0[0]; // Create a new CloudantClient instance for account endpoint <ACCOUNT>.cloudant.com CloudantClient client = ClientBuilder.account(ACCOUNT).username(USERNAME).password(PASSWORD).build(); // Get a Database instance to interact with. Do not create it if it doesn't already exist Database db = client.database(db_name, false); // Get an ExampleDocument out of the database and deserialize the JSON into a Java type user = db.find(user.class, id);
catch (Exception e) e.printstacktrace(); return user; @Override protected void onpostexecute(user user) super.onpostexecute(user); EditText responseedittext = (EditText) findviewbyid(r.id.responseedittext); if (user!= null) responseedittext.settext("read user from DB:\n" + "ID: " + user.getid() + "\n" + "FirstName: " + user.getfirstname() + "\n" + "LastName: " + user.getlastname() + "\n" + "Creation Date: " + user.getcreationdate().tostring() + "\n" + "Age: " + user.getage() + "\n" ); else responseedittext.settext("user not found"); 10. Call the methods setupwritebutton() and setupreadbutton() at the end of the oncreate method: protected void oncreate(bundle savedinstancestate) super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); setupwritebutton(); setupreadbutton(); 11. Create a new class. Name it User // A Java class that can be serialized to JSON public class User private String _id; private String firstname; private String lastname; private Date creationdate; private int age; public User() new User("firstNameTest", "lastnametest", new Date(), -1); public User(String firstname, String lastname, Date creationdate, int age) this._id = UUID.randomUUID().toString(); this.firstname = firstname; this.lastname = lastname; this.creationdate = creationdate; this.age = age;
public String getid() return _id; public String getfirstname() return firstname; public void setfirstname(string firstname) this.firstname = firstname; public String getlastname() return lastname; public void setlastname(string lastname) this.lastname = lastname; public Date getcreationdate() return creationdate; public void setcreationdate(date creationdate) this.creationdate = creationdate; public int getage() return age; public void setage(int age) this.age = age; 12. Open Gradle Scripts->build.gradle (Module: app). Add the following lines in the dependencies section: compile group: 'com.squareup.okhttp', name: 'okhttp-urlconnection', version: '2.7.5' compile group: 'com.cloudant', name: 'cloudant-client', version: '2.6.0' compile 'com.google.code.gson:gson:2.2.4' 13. We are ready to set up our database. Go to this page: https://newconsole.ng.bluemix.net/ and log in 14. Click on Catalog
15. Select Data & Analytics, and then click on Cloudant NoSQL DB 16. Scroll to the bottom of the page and click on Create 17. Click on Launch
18. Click on Databases and then click on Create Database 19. Give a name to your database and click on Create. 20. Once the new DB is created, click on Permissions
21. Locate and press the Generate API Key button. We will use the API key to communicate with the database programmatically. 22. Once the API key is created, you ll see something like this:
23. Leave that page opened. We will be copying the key and its password to our code. 24. Give read and write permissions to the key you just created 25. Go back to your Android project and locate the following variables: private String DB_NAME = ""; private String ACCOUNT = ""; private String USERNAME = ""; private String PASSWORD = ""; 26. The variable must be initialized with the following values: private String DB_NAME = "<Name you gave to the DB in step 18>"; private String ACCOUNT = "<See below>"; private String USERNAME = "<The Key you generated in step 21>"; private String PASSWORD = "<The password the key was given when generated>"; 27. The value you should assign to the variable ACCOUNT can be found in the URL of the page where you manage your database. The URL has the following format. https://<your account ID>.cloudant.com/dashboard.html Copy the <Your account ID> section of the URL, and use that to initialize ACCOUNT 28. Add the following to your AndroidManifest.xml file: <uses-permission android:name="android.permission.internet" />
29. Test your app