In this tutorial we will show you how to integrate Dropbox api with your android app and get all the file or folder from your Dropbox space to your own app.
First download the Dropbox sdk for android from
HERE.
Now go to Apps Console from
HERE. Here select the app type as "core". Write your app name in the space provided. You have two types of permission here: "app folder" & "full dropbox". Select app folder if you want to access a specific folder only from your Dropbox account or "full dropbox" if you want access of all the folder/files in your Dropbox account. Here you will get your "app key" and "app secret". Note these, as you will need this for your app.
Now create a new android project in Eclipse IDE.
Once you have the app keys, we'll need to enter the following snippet in your AndroidManifest.xml in order for the Dropbox SDK to finish the authentication process. Insert the following code under the <application>
section, replacing APP-KEY
with your app key:
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboard">
<intent-filter>
<!-- Change this to be db- followed by your app key -->
<data android:scheme="db-INSERT-APP-KEY-HERE" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Also make sure that your app has the internet permission by ensuring you have the following under the
section of AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Now import all the Dropbox libraries and dependencies in the libs folder into your Eclipse project. To add the libraries to your build path, perform the following actions in Eclipse:
Right click on your project from the Package Explorer and go to Properties.
Select Java Build Path from the sidebar.
Add External JARs and add the libraries.
Now you're all set to start interacting with the Dropbox Java and Android SDKs. Continue on to the next tutorial for more on the authentication process and to get started using the API methods.
We'll need to put your app key and app secret in your code so we can use them to create a session and access your Dropbox account and the API. Replace INSERT_APP_KEY_HERE
and INSERT_SECRET_HERE
with your app key and app secret in the code below.
final static private String APP_KEY = "INSERT_APP_KEY_HERE";
final static private String APP_SECRET = "INSERT_SECRET_HERE";
When you created an app, you were prompted to decide whether you wanted to create your own app folder in the user's Dropbox (APP_FOLDER
) or whether you wanted full Dropbox access (DROPBOX
). Insert your choice here where it says INSERT_APP_ACCESS_TYPE_HERE
.
final static private AccessType ACCESS_TYPE = AccessType.INSERT_APP_ACCESS_TYPE_HERE;
Create a Dropbox session
The app keys are in place, now let's use them to create a new session. We'll use this session to create a new DropboxAPI object called mDBApi. You probably want to keep one of these around as an instance variable.
// 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);
Start the authentication process
The next step in the process is for the user to authorize your app through either the official Dropbox mobile app or via the Dropbox mobile web site. The user will be sent to a screen with your app icon and name and buttons to allow or deny access to their Dropbox. If authenticated, your session will have the user's access token pair to use with API calls. Here we get the session and start the authentication process. startAuthentication() is a function that redirects the user to the Dropbox mobile app or, failing to identify its install, redirects to the mobile website for user authorization via the default mobile browser.
// MyActivity below should be your activity class name
mDBApi.getSession().startAuthentication(MyActivity.this);
Return to your app after user authorization
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.
Please note, it's important that the order and the timing of these calls stay the same. In fact, it might be easier to just copy this code verbatim rather than writing it from scratch.
protected void onResume() {
super.onResume();
// ...
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// MANDATORY call to complete auth.
// Sets the access token on the session
mDBApi.getSession().finishAuthentication();
AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();
// Provide your own storeKeys to persist the access token pair
// A typical way to store tokens is using SharedPreferences
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
// ...
}
The finishAuthentication() method will bind the user's access tokens to the session. You'll now be able to retrieve them via mDBApi.getSession().getAccessTokenPair().
You'll need these tokens again after your app closes, so it's important to save them for future access. If you don't, the user will have to re-authenticate every time they access their Dropbox from your app.
A common way to implement storing keys is through Android's SharedPreferences API. To learn how, check out the Android documentation. In the meantime, for simplicity, the code above pretends the storeKeys function invokes whatever method you'd like to use to store your keys in a more permanent location.
If in the process of authenticating you run into an error message like "Another app on your phone may be trying to pose as the app you are currently using." it means more than one app installed on the phone has a callback activity registered for a single app key. You can fix this error by deleting one of the offending apps or by switching to a new app key.
Getting the folder listing:
To get the Dropbox folder listing follow the below code snippet.
try{
ArrayList<String> folderName=new ArrayList<String>;
Entry dropboxDir1 = mApi.metadata("/", 0, null, true, null);
if (dropboxDir1.isDir) {
List<Entry> contents1 = dropboxDir1.contents;
if (contents1 != null) {
folderName.clear();
for (int i = 0; i < contents1.size(); i++) {
Entry e = contents1.get(i);
String a = e.fileName();
if(String.valueOf(e.isDir).equalsIgnoreCase("true")){
folderName.add(a);
}
}
}
}}catch (Exception ex) {
}
The folder listing will be store in "folderName" ArrayList. Now we will get the files under a particular folder. So here is the code:
try{
ArrayList<String> file_name=new ArrayList<String>;
Entry dropboxDir1 = mApi.metadata("/"+folderName.get(pos), 0, null, true, null);
if (dropboxDir1.isDir) {
System.out.println("___isdir");
List<Entry> contents1 = dropboxDir1.contents;
if (contents1 != null) {
file_name.clear();
for (int i = 0; i < contents1.size(); i++) {
Entry e = contents1.get(i);
String a = e.path;
file_name.add(a);
}
}
}}catch (Exception ex) {
}
The file list will be store in "file_name" ArrayList.
Download a file:
To download a file follow the below code snippet:
FileOutputStream outputStream = null;
try {
sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath()+"/temp");
outputStream = new FileOutputStream(file);
@SuppressWarnings("unused")
DropboxFileInfo info = mApi.getFile(file_name.get(0), null, outputStream, null);
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
System.out.println("___"+e);
}
}
}
Now you can get the file from "outputStream". Now you can use the file as needed.