Using the Core API on Android

The Core API is based on HTTP and OAuth and provides low-level calls to access and manipulate a user's Dropbox account.

If you want to follow along, first register a new app on the App Console. You'll need the app key to access the Core API. Then install the Android SDK and you'll be ready to go.

Authenticating your app

The Core API uses OAuth v1, but the Android SDK will take care of most of it so you don't have to start from scratch.

You'll need to provide your app key and secret as well as the permission you selected when creating the app. The permission will be represented by the AccessType enum (either APP_FOLDER or DROPBOX).

final static private String APP_KEY = "INSERT_APP_KEY";
final static private String APP_SECRET = "INSERT_APP_SECRET";
final static private AccessType ACCESS_TYPE = AccessType.INSERT_APP_ACCESS_TYPE;

Pass all three values to the new DropboxAPI object.

// In the class declaration section:
private DropboxAPI<AndroidAuthSession> mDBApi;

// And later in some initialization function:
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);

Now we're all set to start the authentication flow. We'll start by calling the startOAuth2Authentication() method which will ask the user to authorize your app. If the Dropbox app is installed, the SDK will switch to it so the user doesn't have to sign in, and it will fallback to the browser if not.

// MyActivity below should be your activity class name
mDBApi.getSession().startOAuth2Authentication(MyActivity.this);

Upon authentication, users are returned to the activity from which they came. To finish authentication after the user returns to your app, you'll need to put the following code in your onResume function.

protected void onResume() {
    super.onResume();

    if (mDBApi.getSession().authenticationSuccessful()) {
        try {
            // Required to complete auth, sets the access token on the session
            mDBApi.getSession().finishAuthentication();

            String accessToken = mDBApi.getSession().getOAuth2AccessToken();
        } catch (IllegalStateException e) {
            Log.i("DbAuthLog", "Error authenticating", e);
        }
    }
}

The finishAuthentication() method will bind the user's access token to the session. You'll now be able to retrieve it via mDBApi.getSession().getOAuth2AccessToken().

You'll need this token again after your app closes, so it's important to save it for future access (though it's not shown here). If you don't, the user will have to re-authenticate every time they use your app. A common way to implement storing keys is through Android's SharedPreferences API.

If you've made it this far, you have a simple app that uses the Core API to link to a Dropbox account. Next, we'll upload a file to Dropbox, get its metadata, and then download it back to our app.

Uploading files

Let's say we're building a text editing app and we want to use it to save your latest magnum opus to Dropbox. Let's browse the methods in the Javadoc to see which one will do that for us. This page lists all the methods supported in the SDK. If you scroll down, you'll find putFile.

putFile takes a path pointing to where we want the file on our Dropbox, an InputStream to be uploaded there, and the input's length. For this example, let's upload a local copy of working-draft.txt:

File file = new File("working-draft.txt");
FileInputStream inputStream = new FileInputStream(file);
Entry response = mDBApi.putFile("/magnum-opus.txt", inputStream,
                                file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);

If all goes well, the data in your local working-draft.txt will now be in the root of your app folder (or Dropbox folder, depending on your app's access type). The variable response will be an Entry object containing the metadata of the newly uploaded file. In this case, we're outputting the rev of the newly uploaded file so the output in LogCat should look like this:

The uploaded file's rev is: 362e2029684fe

Listing folders

Now that your file is in Dropbox, let's glance at the file's metadata by invoking the metadata method.

Entry existingEntry = mDBApi.metadata("/magnum-opus.txt", 1, null, false, null);
Log.i("DbExampleLog", "The file's rev is now: " + existingEntry.rev);

Metadata returns information relating to the file, including the file size, path, last modified date, and a revision. For a full list, see the metadata docs. The output from the sample code here should return something like this:

The file's rev is now: 2653b105684af

Downloading files

Some time has passed and you're ready to start editing that magnum opus of yours again. We'll need the getFile method to download the file.

File file = new File("/magnum-opus.txt");
FileOutputStream outputStream = new FileOutputStream(file);
DropboxFileInfo info = mDBApi.getFile("/magnum-opus.txt", null, outputStream, null);
Log.i("DbExampleLog", "The file's rev is: " + info.getMetadata().rev);

Just like the putFile method, we're using a dummy output stream to handle the file contents. In addition to the file, getFile will return DropboxFileInfo, including an entry for metadata.

In addition, we're also logging the rev. Every time a change is made to the file, the rev field of the file's metadata changes as well. By saving the revision when you download the file, you'll be able to tell if that file has been updated by another computer or device and choose to download the newer revision of that file.