Upload Files to Dropbox using Core API Android Tutorial

Udemy Generic 728x90

Objective

In this tutorial we will learn how to upload files to Dropbox from an Android app using Core API through simple example.

 

 

Dropbox is file hosting service that allows user to keep and share docs, photos and videos safely. User can access their photos, docs, video, etc. anywhere using Dropbox.

In this tutorial, we will learn how to integrate Dropbox Core API in Android Application and upload files to the Dropbox. We need app key and secret key to access the Core API. To get app key and secret key, we need to register our app at Dropbox developer console.

 

Step 2

Create New Project

Create a new project in Android Studio, goto File ⇒ New ⇒ New Projects.

 

Step 3

Download Core API SDKs

To use the Core API, download the Dropbox Android SDK and also we need to add Json Simple jar file to handle Json type request and response in your android project library(app/libs) folder.

 

Step 4

Add SDK as Dependency

To use features of Core API, we need to compile SDK in project. So, add Dropbox SDK and json_simple jar files as project dependencies. Open build.gradle file and add files as dependencies as shown below:

dependencies {
   ...
    compile files('libs/dropbox-android-sdk-1.6.3.jar')
    compile files('libs/json_simple-1.1.jar')
   ...
}

 

Step 5

Register New App on App console

To register new app on App console follow below steps:

  • Go to App Console and click on Create App button to create a new app.

    create_app
  • Select Dropbox API App and set permission to access files or folders, select Yes and enter app name in the Provide app name field.

    create_new_dropbox_app
  • Now, click on the create app button to successfully add app on App Console.

    app_created

 

Step 6

Enable Additional Users

By default app is in development status and has all the features available to use as production status. Only limitation of development status is that app can be used only by test users. App can be used by up to 100 test users in development status. To make app accessible to test users, click on Enable Additional Users button. If you want to share app with the world, apply for production status.

enable_additional_user
 

Step 7

Add App Permissions

Our Android App needs Internet service to upload the files to Dropbox from Android device. So, we need to provide Internet permission and also Read and Write Storage permission to read or write files from device’s external storage. Open your AndroidManifest.xml file and add the following code:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 

Step 8

Add Dropbox Client AuthActivity

Next, we need to authenticate Dropbox client in app to provide access to Dropbox cloud. So, add AuthActivity of library in your application’s manifest file and provide API key created during the app creation process at Dropbox app console. Open AndroidManifest.xml file and add AuthActivity inside <application> tag to finish the authentication process after app got installed on the device.

Here is the code snippet to implement AuthActivity in manifest file :

&lt;activity
  android:name=&quot;com.dropbox.client2.android.AuthActivity&quot;
  android:launchMode=&quot;singleTask&quot;
  android:theme=&quot;@android:style/Theme.Translucent.NoTitleBar&quot;
  android:configChanges=&quot;orientation|keyboard&quot;&gt;
  &lt;intent-filter&gt;
    &lt;!-- Change this to be db- followed by your app key --&gt;
    &lt;data android:scheme=&quot;db-INSERT_APP_KEY&quot; /&gt;
    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;
    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot;/&gt;
    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;
  &lt;/intent-filter&gt;
&lt;/activity&gt;

 

Step 9

Create Layout

We will upload file from Android device to Dropbox cloud on button’s click event. So, add a Button widget in the activity_main.xml file.

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    tools:context=&quot;app.dropboxapp.MainActivity&quot;&gt;

    &lt;Button
        android:id=&quot;@+id/uploadfile&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;Upload File&quot;
        android:onClick=&quot;uploadFiles&quot;/&gt;

&lt;/RelativeLayout&gt;

 

upload button

Step 10

Define App Key and Secret Key

To access Core API, you need to add App key and Secret key in the MainActivity.java file.

// Replace APP_KEY with your APP_KEY
final static private String APP_KEY = &quot;idzvjf1ekzxxxx&quot;;
// Relace APP_SECRET with your APP_SECRET
final static private String APP_SECRET = &quot;5nlu9hobyzxxxx&quot;;

 

Step 11

Initialize the Session of the Key pair

To upload or download files from Dropbox, first we need to create connection between your app and Dropbox cloud. Once a connection is established, Dropbox API will start a session. During this session, you can easily upload or download files from Dropbox. To start a session with connection to Dropbox cloud, we need to authenticate the session using the APP_KEY and APP_SECRET defined above.

So, add a method in main activity class, named initialize_session to authenticate and start session. To authenticate session, Dropbox SDK provides a class, named AndroidAuthSession. Add an object of AndroidAuthSession class inside the method and pass pair of APP_KEY and APP_SECRET to it. This will start the authentication process. If Dropbox app is installed on the device, then SDK will switch to Dropbox app otherwise it will fallback to the browser. In this example, Dropbox app is not installed hence it fallback to browser.

Here is the code snippet for the same :

public class MainActivity extends AppCompatActivity {

    // Replace APP_KEY from your APP_KEY
    final static private String APP_KEY = &quot;idzvjf1ekzxxxx&quot;;
    // Relace APP_SECRET from your APP_SECRET
    final static private String APP_SECRET = &quot;5nlu9hobyzxxxx&quot;;

    private DropboxAPI&lt;AndroidAuthSession&gt; mDBApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // callback method
        initialize_session();
    }

    /**
     *  Initialize the Session of the Key pair to authenticate with dropbox
     *  Start the authentication flow.
     *  If Dropbox app is installed, SDK will switch to it otherwise it will fallback to the browser.
     */
    protected void initialize_session(){

        // store app key and secret key
        AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
        AndroidAuthSession session = new AndroidAuthSession(appKeys);

        // Pass app key pair to the new DropboxAPI object.
        mDBApi = new DropboxAPI&lt;AndroidAuthSession&gt;(session);

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

open browser

  • Fill your Email Id and Password to authenticate your app with Dropbox.

    fill email
  • Click on the Allow button to provide access to use App inside your Dropbox.

    allow access to dropbox

 

Step 12

Finish Authentication

We will finish the authentication once user returns to app by using finishAuthentication() method. It binds the user access token retrieved via mDBApi.getSession().getOAuth2AccessToken() to the session. If we do not want to re-authenticate every time user uses the app to download or upload then we have to store token in the SharedPreferences. For the purpose of this example we will not be saving the token.

Use the following code in onResume() method:

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

        if (mDBApi.getSession().authenticationSuccessful()) {
            try {

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

                // retrieve access token
                String accessToken = mDBApi.getSession().getOAuth2AccessToken();

            } catch (IllegalStateException e) {
                Log.i(&quot;DbAuthLog&quot;, &quot;Error authenticating&quot;, e);
            }
        }
    }

 

Step 13

Upload Files

Now, we can upload any type of file from Android device to Dropbox by using putFile method. It takes the path of folder where you want to store the file on the Dropbox, an InputStream to be uploaded there and input length.

putFile makes a network call through the Core API, so implement this method asynchronously.

/**
 *  Asynchronous method to upload any file to dropbox
 */
 public class Upload extends AsyncTask&lt;String, Void, String&gt; {

     protected void onPreExecute(){}

     protected String doInBackground(String... arg0) {

          DropboxAPI.Entry response = null;

          try {

                // Define path of file to be upload
                File file = new File(&quot;/storage/sdcard0/Pictures/Screenshots/screen.png&quot;);
                FileInputStream inputStream = new FileInputStream(file);

                // put the file to dropbox
                response = mDBApi.putFile(&quot;/screens.png&quot;, inputStream,
                        file.length(), null, null);

                Log.e(&quot;DbExampleLog&quot;, &quot;The uploaded file's rev is: &quot; + response.rev);

            } catch (Exception e){

                e.printStackTrace();
            }

            return response.rev;
        }

        @Override
        protected void onPostExecute(String result) {

            if(result.isEmpty() == false){

                Toast.makeText(getApplicationContext(), &quot;File Uploaded &quot;, Toast.LENGTH_LONG).show();

                Log.e(&quot;DbExampleLog&quot;, &quot;The uploaded file's rev is: &quot; + result);
            }
        }
    }

If there is no error, the data in your local screen.png file will now be in the root of your app folder. Entry object contains variable response of the newly uploaded file. In this case, we are going to display output of the newly uploaded file in Logcat. So, output should look like this:

send file

Step 14

Create a Callback method

We need to create a callback method uploadFiles() to execute the method asynchronously. Use the following code in MainActivity.java file

/**
 * Callback register method to execute the upload method
 * @param view
 */
 public void uploadFiles(View view){

      new Upload().execute();
    }

 

Step 15

Final Code

Here is the final code of MainActivity.java file:

public class MainActivity extends AppCompatActivity {

    // Replace APP_KEY from your APP_KEY
    final static private String APP_KEY = &quot;idzvjf1ekzxxxx&quot;;
    // Relace APP_SECRET from your APP_SECRET
    final static private String APP_SECRET = &quot;idzvjf1ekzxxxx&quot;;

    private DropboxAPI&lt;AndroidAuthSession&gt; mDBApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // callback method
        initialize_session();
    }

    /**
     *  Initialize the Session of the Key pair to authenticate with dropbox
     *
     */
    protected void initialize_session(){

        // store app key and secret key
        AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
        AndroidAuthSession session = new AndroidAuthSession(appKeys);

        //Pass app key pair to the new DropboxAPI object.
        mDBApi = new DropboxAPI&lt;AndroidAuthSession&gt;(session);

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

    /**
     * Callback register method to execute the upload method
     * @param view
     */
    public void uploadFiles(View view){

        new Upload().execute();
    }

    /**
     *  Asynchronous method to upload any file to dropbox
     */
    public class Upload extends AsyncTask&lt;String, Void, String&gt; {

        protected void onPreExecute(){

        }

        protected String doInBackground(String... arg0) {

            DropboxAPI.Entry response = null;

            try {

                // Define path of file to be upload
                File file = new File(&quot;/storage/sdcard0/Pictures/Screenshots/screen.png&quot;);
                FileInputStream inputStream = new FileInputStream(file);

                // put the file to dropbox
                response = mDBApi.putFile(&quot;/screens.png&quot;, inputStream,
                        file.length(), null, null);

                Log.e(&quot;DbExampleLog&quot;, &quot;The uploaded file's rev is: &quot; + response.rev);

            } catch (Exception e){

                e.printStackTrace();
            }

            return response.rev;
        }

        @Override
        protected void onPostExecute(String result) {

            if(result.isEmpty() == false){

                Toast.makeText(getApplicationContext(), &quot;File Uploaded &quot;, Toast.LENGTH_LONG).show();

                Log.e(&quot;DbExampleLog&quot;, &quot;The uploaded file's rev is: &quot; + result);
            }
        }
    }

    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(&quot;DbAuthLog&quot;, &quot;Error authenticating&quot;, e);
            }
        }
    }
}

Udemy Generic 728x90

Spread the word. Share this post!

  • Dhruv Rathi

    Great tutorial, loved it :)