In this tutorial we will learn how to create an Android application for uploading a file on Dropbox!
Dropbox is a popular free service that helps share your files easily. It also provides certain API’s that developers can use to create applications that upload files directly on Dropbox. In order to connect to Dropbox, you first need to Create an Account on their website. Once the account is created you need to visit the Dropbox App console.
Tutorial Pre-requisites: Eclipse IDE, Dropbox account, Android SDK
Step 1:
Obtain API key and secret
On the App Console screen, click Create App and choose to create a new Dropbox API App. Select type of data as Files and Datastores and choose the option toaccess files the app will eventually create. Next, you need to provide an application name and Dropbox will generate an API key and secret for your application.
Step 2:
Download Dropbox Android SDK
In order to use Dropbox functionalities, we need to download the Android SDK for Dropbox from over here. Add the .jar files that are required inside the libs folder once you create an Android project.
Step 3:
Create Android project
Create a new Android application project called AndroidDropboxExample. Add the following Activity class in your src folder.
MainActivity.java
package com.app.dropbox;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.dropbox.client2.session.TokenPair;
public class MainActivity extends Activity implements OnClickListener {
private DropboxAPI dropbox;
private final static String FILE_DIR = “/MySampleFolder/”;
private final static String DROPBOX_NAME = “dropbox_prefs”;
private final static String ACCESS_KEY = “YOUR_API_KEY”;
private final static String ACCESS_SECRET = “YOUR_API_SECRET”;
private boolean isLoggedIn;
private Button login;
private Button uploadFile;
@SuppressWarnings(“deprecation”)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.dropbox_login);
login.setOnClickListener(this);
uploadFile = (Button) findViewById(R.id.upload_file);
uploadFile.setOnClickListener(this);
loggedIn(false);
AndroidAuthSession session;
AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
String key = prefs.getString(ACCESS_KEY, null);
String secret = prefs.getString(ACCESS_SECRET, null);
if (key != null && secret != null) {
AccessTokenPair token = new AccessTokenPair(key, secret);
session = new AndroidAuthSession(pair, AccessType.APP_FOLDER, token);
} else {
session = new AndroidAuthSession(pair, AccessType.APP_FOLDER);
}
dropbox = new DropboxAPI(session);
}
@Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = dropbox.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
Editor editor = prefs.edit();
editor.putString(ACCESS_KEY, tokens.key);
editor.putString(ACCESS_SECRET, tokens.secret);
editor.commit();
loggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(this, “Error during Dropbox authentication”,
Toast.LENGTH_SHORT).show();
}
}
}
public void loggedIn(boolean isLogged) {
isLoggedIn = isLogged;
uploadFile.setEnabled(isLogged);
login.setText(isLogged ? “Logout” : “Login”);
}
@SuppressWarnings(“deprecation”)
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dropbox_login:
if (isLoggedIn) {
dropbox.getSession().unlink();
loggedIn(false);
} else {
dropbox.getSession().startAuthentication(MainActivity.this);
}
break;
case R.id.upload_file:
UploadFileToDropbox upload = new UploadFileToDropbox(this, dropbox,
FILE_DIR);
upload.execute();
break;
default:
break;
}
}
}
UploadFileToDropbox.java
package com.app.dropbox;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.exception.DropboxException;
public class UploadFileToDropbox extends AsyncTask<Void, Void, Boolean> {
private DropboxAPI<?> dropbox;
private String path;
private Context context;
public UploadFileToDropbox(Context context, DropboxAPI<?> dropbox,
String path) {
this.context = context.getApplicationContext();
this.dropbox = dropbox;
this.path = path;
}
@Override
protected Boolean doInBackground(Void… params) {
final File tempDir = context.getCacheDir();
File tempFile;
FileWriter fr;
try {
tempFile = File.createTempFile(“file”, “.txt”, tempDir);
fr = new FileWriter(tempFile);
fr.write(“Test file uploaded using Dropbox API for Android”);
fr.close();
FileInputStream fileInputStream = new FileInputStream(tempFile);
dropbox.putFile(path + “sample.txt”, fileInputStream,
tempFile.length(), null, null);
tempFile.delete();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(context, “File Uploaded Successfully!”,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, “Failed to upload file”, Toast.LENGTH_LONG)
.show();
}
}
}
In order to configure your Android application to use Dropbox features, we need to add the following Activity in the AndroidManifest.xml file.
AndroidManifest.xml
activity_main.xml