How to Integrate Dropbox with your Android APP and Perform CRUD Action

Integrate Dropbox with your Android APP and Perform CRUD Action

Main objective of this blog is to give you more detail information about how to Integrate Dropbox with your Android APP and Perform CRUD Action.

#1

Introduction of The Tools

For Developing an Android application, we use an Android Studio, which allows the applications to be developed in a Java Language Environment.

#2

Setting Up The Environment.

In Android Studio, create a new project by navigating to File ⇒ New Project and fill all the required details. When it prompts to select a default activity, select Blank Activity and proceed.

#3

Integrate Dropbox With Your Android App.

What is DROPBOX?

Dropbox is a cloud storage wherein we can store photos, videos, documents, and files. We can access these files from any computer and from anywhere.

To Integrate the DROPBOX API in your android application, follow the following steps:

In this tutorial, The first screen will be – PickImageActivity To select an image and show on the screen.

After selecting an image, We will code for uploading the Image on Your Dropbox Account. Make sure you have Dropbox app installed on your Android device.

So after selecting an image, the Dropbox login screen will be opened. Once you are logged in, you will be redirected to The Second Screen.

To support the uploading, the Dropbox documentation provides the following java files:

A

DropboxClientFactory To initialize the client

B

PicassoClient Configure picasso to know about special thumbnail requests

C

UploadFileTask Async task to upload a file to a Dropbox

D

UriHelpers Utility functions to support Uri conversion and processing.

The Second Screen will be MainActivity This has the code to upload the image to Dropbox.

1. Create a New Project in Android Studio

Create a New Project in Android Studio

2. Select Your Platform and Proceed.

Select Your Platform and Proceed

3. Select an Activity and Name it

  • Select an Activity
    Select an Activity
  • Customize the Activity
    Customize the Activity

4. To Use the Dropbox API

First of all, in your project, add the following permissions in your AndroidManifest file.

<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" />

5. Now in a build.gradle file add the Following:

dependencies {
    compile 'com.dropbox.core:dropbox-core-sdk:0-SNAPSHOT'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.dropbox.core:dropbox-core-sdk:2.1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.okhttp:okhttp:2.7.5'
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    compile files('libs/json_simple-1.1.jar')
    compile 'com.squareup.okhttp:okhttp:2.0.0'
}

6. Add the Line to Avoid Conflict

In the same build.gradle file adds the lines to avoid a conflict during build time of multiple License.txt or Notice.txt files because sometimes android studio considers duplicate entry lib’s and gives error while packaging.

packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
}

7. Now Open App Console

Go to the https://www.dropbox.com/developers/apps And create the new app
Open App Console

8. Click on “CREATE APP”

Click on “CREATE APP”

9. Now Click on “DROPBOX API”

  • Choose the type of access and give the name of your app and click on “CREATE APP”. Now your app is created on the console and you can access your keys through it.
  • Save your “APP KEY “ and “APP SECRET” as it will be used in your Android Application.

 

 

10. Open Your Project in Android Studio and in Your Manifest file, Add

<activity
    android:name="com.dropbox.client2.android.AuthActivity"
    android:configChanges="orientation|keyboard"
    android:launchMode="singleTask" >
    <intent-filter>
 
        <data android:scheme="db-********" />

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Add an activity in manifest file which will be used to authenticate your application. Change the android:scheme to db – followed by your app key.

11. Now The First Screen of App is PickImageActivity.

Open your activity_pick_image and add the components: Two Buttons to select and upload and an ImageView to view the selected image.
PickImageActivity

12. Add the OnClickListner for Selecting Image.

Here we check the version of Android on the device so accordingly the code works.

btnPickImage.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (isKitKat) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "SELECT"), 1);
        } else {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"SELECT"), 1);
        }
    }
});

13. Now we add onActivityResult.

By using this method we get the path of the image. Store the path of the image in the variable strImagePath.

14. Now We set the Image on ImageView.

File f = new File(strImagePath);

    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    Bitmap bitmap =  BitmapFactory.decodeFile(f.getAbsolutePath(),bmOptions);
    iv.setImageBitmap(bitmap);

15. Now Extract The Name of The Image From The Path and Store It in a String.

String result1 = strImagePath.substring(strImagePath.lastIndexOf("/") + 1);

I have kept the button upload hidden till the path is obtained. So once you get the result1, use this to show the button upload

btn_upload.setVisibility(View.VISIBLE);

16. We Need to Use Runtime Permissions.

Add check self-permission.

pickImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                } else {
                    selectImage();
                }
            }
        });

So we are done with image loading in our First Screen

Now We Check Step by Step How to Upload it to The Dropbox

Step 1: Use Dropbox Initialization. (Refer MainActivity.Java)

Step 2: Code For Asynchornous Task for Image Upload (Refer UploadFileTask.Java)

Step 3: On Click Of The Button, we upload the image on the DROPBOX (Refer activity_main.xml and uploadFile(uri_get); method in MainActivity.Java)

Step 4: Initialize the Session of the Key pair to authenticate with Dropbox.

private DropboxAPI<AndroidAuthSession> mDBApi;
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<>(session);
    // MyActivity below should be your activity class name
    //start session
    mDBApi.getSession().startOAuth2Authentication(MainActivity.this);

}

Step 5: For Asynchronous Task For Image Upload

class UploadFileTask extends AsyncTask<String, Void, FileMetadata> 

And in this class, we code for file upload.

@Override
protected FileMetadata doInBackground(String... params) {
    String localUri = params[0];
    File localFile = UriHelpers.getFileForUri(mContext, Uri.parse(localUri));

    Log.e("localFile",""+localFile);

    if (localFile != null) {

        // Note - this is not ensuring the name is a valid dropbox file name
        String remoteFileName = localFile.getName();

        try  {


            InputStream inputStream = new FileInputStream(localFile);
            return mDbxClient.files().uploadBuilder(  "/" + remoteFileName)
                    .withMode(WriteMode.OVERWRITE)
                    .uploadAndFinish(inputStream);
        } catch (DbxException | IOException e) {
            mException = e;
        }
    }

    return null;
}

Now our code for uploading is ready.

Step 6: activity_mail.xml

In our activity_main.xml, we have a button to upload the image to Dropbox.
We have stored the path and URI of the image in shared preference.

SharedPreferences sp = this.getSharedPreferences("IMAGEPATH", MODE_WORLD_READABLE);
strImagePath = sp.getString("strImagePath", "");
result1= sp.getString("result1", "");

SharedPreferences spuri = this.getSharedPreferences("uri_getSP", MODE_WORLD_READABLE);
uri_get = spuri.getString("uri_get", "");

So use this button and inside the onClickListner of the button, call the async task that is the file UploadFileTask.

btn_upload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        uploadFiles();
    }
});

/**
     * Callback register method to execute the upload method
     */
    public void uploadFiles(){



        SharedPreferences sp = this.getSharedPreferences("IMAGEPATH", MODE_WORLD_READABLE);
        strImagePath = sp.getString("strImagePath", "");
        result1= sp.getString("result1", "");


        SharedPreferences spuri = this.getSharedPreferences("uri_getSP", MODE_WORLD_READABLE);
        uri_get = spuri.getString("uri_get", "");
 
       uploadFile(uri_get);
    }





private void uploadFile(String fileUri) {
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    dialog.setMessage("Uploading");
    dialog.show();

    new UploadFileTask(this, DropboxClientFactory.getClient(), new UploadFileTask.Callback() {
        @Override
        public void onUploadComplete(FileMetadata result) {
            dialog.dismiss();

            String message = result.getName() + " size " + result.getSize() + " modified " +
                    DateFormat.getDateTimeInstance().format(result.getClientModified());
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT)
                    .show();


            Toast.makeText(MainActivity.this, "Successfully Uploaded.", Toast.LENGTH_SHORT)
                    .show();

            Intent it=new Intent(MainActivity.this,PickImageActivity.class);
            startActivity(it);

        }

        @Override
        public void onError(Exception e) {
            dialog.dismiss();

            Log.e("ERROR ", "Failed to upload file.", e);
            Toast.makeText(MainActivity.this,
                    "An error has occurred",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    }).execute(fileUri,strImagePath);
}

After this code, Open your DROPBOX APPLICATION installed on your device, and reload it.

You can see the uploaded file there.

dropbox-integration

This is how we use DROPBOX API V2. If you are using API V1, The Shift to V2 as V1  is deprecated and doesn’t work.

Experienced Android Developer with a demonstrated history of working in the computer software industry. Expert Android Trainer at Code Kaksha. Skilled in Android, Eclipse, XML, Android Development, and Android Studio. Strong engineering professional with a Bachelor’s Degree focused in Computer Engineering from C.U.Shah College of Engineering and Technology.
  • rawat praweiad

    i get your dropbox api v2 project but i can not run it i need your helps in MainActivity howto write easy code for upload file with fix file name from my phone .thanks a lot

  • Zack Choon

    Hi there, I found out that the tutorial is useful for me.
    However, I would like to know more about integrating dropbox v2 using android studio.
    can you do a tutorial for that, Thanks

  • Walt Williams

    You mention “build.gradle file” in step 5 above. Which one? I have 2 of them. One is for ‘Project:appName’ and the other is for ‘Module:app’. I’m going to assume the later (Module:app) for now