NimbusBase Android Tutorial

Project Setup

Prerequisites

  1. API level 15 and above

Configuration

Our library is published on Sonatype, so projects can depend on it by adding several lines in the Gradle files.

  1. Capacitate Gradle to find dependencies on Sonatype by adding maven url in your root ‘build.gradle’ file.

     allprojects {
         repositories {
             jcenter()
                 maven {
                     url 'https://oss.sonatype.org/content/groups/public'
                 }
         }
     }
    
  2. Add NimbusBase into the dependencies list in your app’s ‘build.gradle’ file. The attribute transitive means you want your project import NimbusBase’s dependencies recursively.

     dependencies {
         compile fileTree(dir: 'libs', include: ['*.jar'])
         compile ('com.nimbusbase:nimbusbaseandroid:1.0-SNAPSHOT@aar') {
             transitive = true
         }
     }
    
  3. To enable the cloud service, add relative SDKs provided by supported clouds.

     dependencies {
         compile fileTree(dir: 'libs', include: ['*.jar'])
         compile ('com.nimbusbase:nimbusbaseandroid:1.0-SNAPSHOT@aar') {
             transitive = true
         }
            
         compile 'com.google.android.gms:play-services:6.1.11'
         compile project(':Libraries:BoxAndroidLibraryV2')
         compile fileTree(dir: '../Libraries/DropboxClient2/lib', include: ['*.jar'])
     }
    

For more specific instructions, please consult our open source demo app.

Usage

Config

All the magic of NimbusBase begins with class Base. You should construct it with app context, database entrance and a config map.

Base base = new Base(<Context>, <SQLiteOpenHelper>, <Map>);

All the keys supposed to be used in the config map are defined in the nested classes of class Constant.

Key Legal values Description
SERVERS <List> Set of servers’ information will be setup.
APP_NAME <String> Name of your app, will be used to name the app folder on cloud.
CLOUD GDRIVE | DROPBOX | BOX Cloud provider type.
APP_ID <String> ID of your app, can be retrieved from app console of the cloud provider.
APP_SECRET <String> Secret of your app, can be retrieved from app console of the cloud provider.
AUTH_SCOPE ROOT | APP_DATA Indicate whether you want to access all data on the cloud or just the data it creates.

A demo of config dictionary:

new HashMap<String, Object>() { {
    put(Config.SERVERS,
            new ArrayList<Map<String,Object>>() { {
                    add(new HashMap<String, Object>() { {
                            put(Config.CLOUD, Config.DROPBOX);
                            put(Config.APP_NAME, "your_app_name");
                            put(Config.APP_ID, "your_app_id_from_dropbox");
                            put(Config.APP_SECRET, "your_app_secret_dropbox");
                            put(Config.AUTH_SCOPE, Config.AuthScope.APP_DATA);
                        }}
                    );
            }}
        );
}};

For the details about how to config your project on the cloud providers’ side, consult section Supported Clouds this page and section Usage in the companion tutorial article for iOS.

Setup

In order to work properly, NimbusBase need to be notified from some system events. Hence following pieces of code need to be inserted.

In your main activity, NimbusBase need listen to Activity#onActivityResult and Activity#onResume.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    getNimbusBase().onActivityResult(this, requestCode, resultCode, data);
}

@Override
protected void onResume() {
    super.onResume();
    getNimbusBase().onResume(this);
}

In your subclass of SQLiteOpenHelper, NimbusBase need listen to SQLiteOpenHelper#onOpen.

@Override
public void onOpen(SQLiteDatabase database) {
    Base.setupDataBaseOnOpen(database);
}

Auth

According to the requirements from clouds providers, you need add some <activity> or <meta-data> tags in your ‘AndroidManifest.xml’ to enable your app to popup activities, whereby your users can input their accounts and passwords. For more details, please consult the links presented in section Supported Clouds.

After call method below, a new activity will be presented to request account ID and password from user.

void authorize(Server server, Activity activity) {
    server.authorize(activity);
}

If user succeeds to auth, NimbusBase will keep the access token and authorize automatically without presenting extra activity until the access token expires.

The auth state can be retrieved via getter Server#getAuthState. It’s represented be an enum type defined as follows:

public static enum AuthState {
    SigningIn, In, SigningOut, Out;
}

CRUD (Create, Retrieve, Update, Delete)

After signing in, NimbusBase needs to do some initialization work on the cloud. If it is done, the value returned by getter Server#isInitialized will change to true from false. And only from that point your app is able to CRUD files on the cloud.

The class Server has 5 methods responsible for CRUD operations:

public Promise<List<File>> retrieveFolder(final File file);
public Promise<File> createFile(final File parent, final FileForm fileForm);
public Promise<java.io.File> retrieveFile(final File file);
public Promise<File> updateFile(final File file, final FileForm fileForm);
public Promise<String> deleteFile(final File file);

Class File represents a file on the cloud, which you should never instantiate one by yourself, as they are always returned by an instance of Server. NimbusBase regards folder as file too. The difference is in the callback of retrieving a file, you get an instance of java.io.File as response, but in the callback of retrieving folder you get an instance of List<File>, which contains its sub-files.

Class FileForm is responsible for collecting information of a file when you want to create or update it.

Class Promise manages network operations. You can set done/fail callbacks on it, get its progress and more. After you get an instance of Promise, don’t forget to call method run on it, or nothing will happen.

Here’s a demo about how to create a new folder in the root folder:

protected void createFolderInRoot(String folderName, Server server) {

    final FileForm
            fileForm = FileForm.folder(folderName);
    final File
            root = server.getRoot();

    Promise<File> promise = server
            .createFile(root, fileForm)
            .onDone(new Callback.DoneListener<File>() {
                @Override
                public void onDone(Response<File> response, File result) {
                    Log.v("CRUD", "I created a folder named " + result.getName() + "in root folder");
                }
            })
            .onFail(new Callback.FailListener<File>() {
                @Override
                public void onFail(Response<File> response, NMBError error) {
                    Log.v("CRUD", "Oops! An error occurred when creating the folder: " + error.getMessage());
                }
            });

    server.runPromise(promise);
}

Sync

The sync function is enable once you pass the database entrance of class SQLiteOpenHelper when you instantiate class Base.

To start a sync, select an authorized Server and invoke method Server#synchronize, you can pass null as parameter options if it is a normal sync. The method returns a Promise which you can add callbacks on it just like when you CRUD files.

protected void startSync(Server server) {
    final Promise
            promise = server.synchronize(null);
    promise
            .onProgress(new Callback.ProgressListener() {
                @Override
                public void onProgress(double v) {
                    Log.v("Sync", String.format("The sync has been finished %3.0f", v * 100));
                }
            })
            .onAlways(new Callback.AlwaysListener() {
                @Override
                public void onAlways(Response response) {
                    Log.v("Sync", "The sync has gotten the end with " +
                                    (response.isSuccess() ? "success" : "fail")
                    );
                }
            });
}

Supported Clouds

NimbusBase supports Google Drive, Dropbox and Box currently. You may find following links are helpful for you to setup your projects

Cloud Section about Manifest SDK Dependency
Google Drive Add Google Play Services to Your Project Using Android Studio
Dropbox Adding to existing projects Download Android SDK
Box OAuth 2.0 Box Android SDK

Demo Project

Open source demo

For more specific instructions, please visit our open source demo project on Github.