{ DreamFactory: 'Blog' }

Android SDK

Posted by Connor Foody

Fri, Aug 7, 2015

During my summer internship I worked on DreamFactory’s mobile SDKs. One cool thing (of many) about DreamFactory is they provide a range of client SDKs complete with great documentation and samples. My last blog post was about the work I’ve done with the DreamFactory iOS SDK. I also worked on improving the Android SDK, building a sample app, and enhancing the documentation. You can now find the the new and improved SDK on GitHub. Here are some important things to know when getting started with the Android SDK.

Android SDK 101

The DreamFactory Android SDK provides user-friendly access to both native and remote REST services that you make available through DreamFactory. Wrappers make API calls clean. Designed to be compatible with Android API 15+, the API uses the Apache HttpClient to send REST requests. If the Apache HttpClient doesn’t meet your needs, changing the library used by the DreamFactory Android SDK to something like volley or retrofit is straightforward.

Here are some examples of authentication and database CRUD using the Android SDK.

Login

The SDK provides the BaseAsycRequest class to help build and manage the request. Extend it and override its functions in this request.

 public class UserLoginTask extends BaseAsyncRequest {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}

Override the setup method, which is called before the request is built. The general form of the URL is /rest/service/endpoint. Logging in uses the user service and the session endpoint.

   @Override
protected void doSetup() throws ApiException, JSONException {
callerName = "loginActivity"; // used as a tag in error messages
serviceName = "user";
endPoint = "session";
       // include application name
applicationName = AppConstants.APP_NAME;

Send the login credentials to DreamFactory in the request body. Use an email and password pair to authenticate with DreamFactory.

      // post email and password to get back session id
// need session id to make every call other than login and challenge
      verb = "POST";
requestBody = new JSONObject();
 requestBody.put("email", mEmail);
requestBody.put("password", mPassword);
} // end setup

Process the response from the server if we did not get an error. Check that we got a session_id back and store it for later.

   @Override
protected void process_response(String response) throws ApiException, JSONException {
// store the session_id to be used later on
JSONObject jsonObject = new JSONObject(response);
 String session_id = jsonObject.getString("session_id");
if(session_id.length() == 0){
 throw new ApiException(0, "did not get a valid session id in the response");
}
PrefUtil.putString(getApplicationContext(), AppConstants.SESSION_ID, session_id);
}

If the request completed successfully, move on to the next view. Otherwise, indicate that login failed on the UI. 

   @Override
protected void onCompletion(boolean success) {
mAuthTask = null;
showProgress(false);
if(success){
 showGroupListActivity();
}
 else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
 mPasswordView.requestFocus();
}
}

Getting relational records

In this example we are getting records from a MySQL database for a view that displays the contacts in a certain group. We are using the database service to access relational records from the contact_relationship table.

   serviceName = "db";
endPoint = "contact_relationships";
verb = "GET";

We want to end up with contact records using a groupId. The form of contact_relationship records is {groupId, contactId}. We use a filter to select only contact_relationship records for the group we are displaying. A related param gets the contacts referenced by each relational record.

   queryParams = new HashMap<>();
queryParams.put("filter", "contactGroupId=" + groupId);
queryParams.put("related", "contacts_by_contactId");

The header params provide the application name and a valid session token to authenticate access.

   applicationName = AppConstants.APP_NAME;
sessionId = PrefUtil.getString(getApplicationContext(), AppConstants.SESSION_ID);

Deserialize the response from a JSON string to POJOs using jackson’s mapper. The response is an array of contact_relation records, each with a field containing a contact record. The onCompletion method was excluded for brevity. If the call is successful the onCompletion method displays the list of contacts.

   ContactsRelationalRecords relationalRecords =
(ContactsRelationalRecords) ApiInvoker.deserialize(response,
"",
ContactsRelationalRecords.class);
contactRecords = new ArrayList<>();
for(ContactsRelationalRecord record : relationalRecords.record){
contactRecords.add(record.contacts_by_contact_id);
}

Android SDK sample app

Sample code is available on GitHub showing more database CRUD operations as well as file CRUD operations. The SDK also supports operations on other resources available through DreamFactory, such as user or system objects.

To get started with the sample app, set up DreamFactory using one of the methods listed on the wiki. Import the application:  Screen_Shot_2015-08-07_at_2.53.07_PM

Configure CORS:

Screen_Shot_2015-08-04_at_10.05.56_AM

Point the sample app at your DreamFactory URL and you’re ready to go.

Screen_Shot_2015-08-07_at_4.36.26_PM

More detailed setup instructions are available in the README.

I hope you find the Android SDK, documentation and sample app helpful. If you have any questions or feedback, feel free to let me know by posting to this forum thread.

Get started with DreamFactory with a free hosted DreamFactory development environment. Or, download and run it on the server, cloud, or desktop of your choice.

Sample Apps Tutorials

Weekly Digest

Recent Posts