Integrate OneDrive and Upload file in Android Tutorial

Udemy Generic 728x90

Objective

In this tutorial, we will learn how to integrate OneDrive in Android Application and use OneDrive’s Picker and Saver services to upload and share file to OneDrive cloud through a simple example.

 

 

OneDrive is a online cloud storage service provide by Microsoft using which we can easily save file and view or share them through web from anywhere. OneDrive provides Picker and Saver for Android. Picker provides the service to fetch the file from Dropbox and Saver provides the ability to upload or save file on OneDrive cloud.

In this tutorial, we will learn how to create an app at OneDrive’s developer console and integrate OneDrive SDK in Android Application.  Also, we will learn how to upload the file to OneDrive cloud and pick document from there to share or view them.
 

Step 2

Create New Project

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

Step 3

Register Application to OneDrive

To register and configure application at developer console, follow these steps :

    • Go to the Microsoft account Developer Center.
    • Sign in with your Microsoft account credentials.
    • Click on the Create application
      create application
    • To register application, fill the application name and click on the Accept button.
      registerApp name
    • Before using OneDrive services in Android app, we will have to specify that the application is a mobile client app. For that go to API settings, select Yes option under Mobile or desktop client app and save this setting by click on Save button.
      oneDrive setting
    • To get Client Id or App Id, go to App Setting tab. We will use this Client Id during the integration process of OneDrive SDK to Android application.

 

ClientId
 

Step 4

Add the library as Dependency

To integrate the App with OneDrive, we need to add the supporting library of the OneDrive. Open build.gradle (app module) file and add the library as dependency.

dependencies {
   ...
    compile ('com.microsoft.onedrivesdk:onedrive-picker-android:v2.0')
   ...
}

 

Step 5

Add App Permissions

Our Android App needs Internet service to upload and pick files from OneDrive cloud storage. 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 6

Create Layout

The app will have two functionalities, first to get the details of the file from OneDrive and second, upload the file to OneDrive. These functionalities will get executed on button click. So, we need to use two Button widget. Also, we need to use the TextView in layout to display file details. Use the following code in the activity_main.xml file.

<Button
    android:id="@+id/startPickerButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Pick File to OneDrive" />

<Button
   android:id="@+id/saver"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@+id/startPickerButton"
   android:text="Save File to OneDrive" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/saver"
    android:textSize="20dp"
    android:id="@+id/pic_name"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/pic_name"
    android:id="@+id/pic_link"
    android:textSize="20dp" />

onedrive button

 

Step 7

Add Client ID

To integrate our application with One Drive we need to use OneDrive credentials, for which we need to add the Client Id in MainActivity.java file.

private String ONEDRIVE_Client_ID = "000000004C18xxxxx ";

 

Step 8

Pick the File

To pick the file,  we need to open file using OneDrive app and pick it on button’s click. So,l we need to add click listener to implement onClick() method. In this method, create the Picker by using createPicker() method and pass the client id as parameter to it. Next, configure the type of link requested by user to launch the file picking process by using startPicking() method. If the users do not have the OneDrive app installed when startPicking() is invoked, they will be prompted to download the app from the app store.

public class MainActivity extends AppCompatActivity {

    private IPicker mPicker;
    private String ONEDRIVE_Client_ID = "000000004C1xxxxxxx ";
    private boolean picker = false;

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

        // Call the listener method to pick the image
        ((Button)findViewById(R.id.startPickerButton))
                   .setOnClickListener(mStartPickingListener);
    }

    /**
     * The onClickListener that will start the OneDrive picker
     * */
    private final View.OnClickListener mStartPickingListener = new View.OnClickListener() {
        @Override
        public void onClick(final View v) {

            picker = true;
            mPicker = Picker.createPicker(ONEDRIVE_Client_ID);

            // open one drive app to pick the file
            mPicker.startPicking((Activity)v.getContext(), LinkType.WebViewLink);
        }
    };
}

upload file from one drive

 

Step 9

Handle the Picker Response

The response from Picker will be handled by onActivityResult() method. When user has picked a file from OneDrive app, we get the result through onActivityResult() and get access to the file selected by the user. This method also handles the result when user cancels a file pick up from OneDrive app.

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {

    // Get the results from the picker
    IPickerResult result = mPicker.getPickerResult(requestCode, resultCode, data);

    // Handle the case if nothing was picked
    if (result != null) {

         // Do something with the picked file
         Log.e("main", "Link to file '" + result.getName() + ": " + result.getLink());
         ((TextView) findViewById(R.id.pic_name)).setText(result.getName());
         ((TextView) findViewById(R.id.pic_link)).setText(result.getLink().toString());

         return;
    }
}

 

Step 10

Save File to OneDrive Cloud

We can also upload and save file to OneDrive cloud storage from app. So, implement onClick() method of button’s click listener and add the code to upload the file within this method. We need to create a new saver instance by using createSaver() method and pass the Client Id in it. To launch saver, call the startSaving() method and pass the file name and URI of the file in it. When OneDrive app is launched then click upload button to upload the file to OneDrive and if the users do not have the OneDrive app installed when startSaving() is invoked, they will be prompted to download the app from the app store.

The saver currently supports the content:// and file:// file URI scheme. If a different URI scheme is used, the saver will return a NoFileSpecified.

/**
 * The onClickListener that will upload file to the OneDrive
 * */
 private final View.OnClickListener FilesaverListener = new View.OnClickListener() {
     @Override
     public void onClick(final View v) {

         picker = false;

         // create example file to save to OneDrive
         final String filename = "files.txt";

         // file path
         File file = new File(Environment.getExternalStorageDirectory() + "/Pictures/", filename);

         Log.e("file", Uri.parse("file://" + file.getAbsolutePath()) +"...." + file);

         // create and launch the saver
         mSaver = Saver.createSaver(ONEDRIVE_Client_ID);
         mSaver.startSaving((Activity)v.getContext(), filename,
                            Uri.parse("file://" + file.getAbsolutePath()));
     }
};

download file from one drive

 

Step 11

Handle the Result of Saver

Once file upload to OneDrive is complete or some problem happened while uploading, onActivityResult() will be called to handle the result.

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {

      // check that the file was successfully saved to OneDrive
      try {

           mSaver.handleSave(requestCode, resultCode, data);

       } catch (final SaverException e) {

            // Log error information
            // SaverError type
            Log.e("OneDriveSaver", e.getErrorType().toString());

       }

       // Handle non-OneDrive picker request
       super.onActivityResult(requestCode, resultCode, data);
}

 

Step 12

Final code

Here is final code of MainActivity file

public class MainActivity extends AppCompatActivity {

    private IPicker mPicker;
    private String ONEDRIVE_Client_ID = "000000004C18257B ";
    private ISaver mSaver;
    private boolean picker = false;

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

        // Call the listener method to pick the image
        ((Button)findViewById(R.id.startPickerButton))
                 .setOnClickListener(mStartPickingListener);

        // Call the listener method to upload the file to OneDrive
        ((Button)findViewById(R.id.saver)).setOnClickListener(FilesaverListener);
    }

    /**
     * The onClickListener that will start the OneDrive picker
     * */
    private final View.OnClickListener mStartPickingListener =
      new View.OnClickListener() {
        @Override
        public void onClick(final View v) {

            picker = true;
            mPicker = Picker.createPicker(ONEDRIVE_Client_ID);
            mPicker.startPicking((Activity)v.getContext(), LinkType.WebViewLink);
        }
    };

    /**
     * The onClickListener that will upload file to the OneDrive
     * */
    private final View.OnClickListener FilesaverListener = new
     View.OnClickListener() {
        @Override
        public void onClick(final View v) {

            picker = false;

            // create example file to save to OneDrive
            final String filename = "files.txt";

            // file path
            File file = new File(Environment
                       .getExternalStorageDirectory() + "/Pictures/", filename);

            Log.e("file", Uri.parse("file://" +
                                   file.getAbsolutePath()) +"...." + file);

            // create and launch the saver
            mSaver = Saver.createSaver(ONEDRIVE_Client_ID);
            mSaver.startSaving((Activity)v.getContext(),
                               filename,  Uri.parse("file://" + file.getAbsolutePath()));
        }
    };

    protected void onActivityResult(final int requestCode,
      final int resultCode, final Intent data) {

        if(picker == true) {

            // Get the results from the picker
            IPickerResult result = mPicker
                                    .getPickerResult(requestCode, resultCode, data);

            // Handle the case if nothing was picked
            if (result != null) {

                // Do something with the picked file
                Log.e("main", "Link to file '" + result
                                 .getName() + ": " + result.getLink());

                ((TextView) findViewById(R.id.pic_name))
                                .setText(result.getName());

                ((TextView) findViewById(R.id.pic_link))
                               .setText(result.getLink().toString());

                return;
            }
        } else {

            // check that the file was successfully saved to OneDrive
            try {

                mSaver.handleSave(requestCode, resultCode, data);

            } catch (final SaverException e) {

                // Log error information
                Log.e("OneDriveSaver",
                            e.getErrorType()
                            .toString()); // Provides one of the SaverError enum
                // Log.d("OneDriveSaver",
                           e.getDebugErrorInfo()); // Detailed debug error message
            }
        }

        // Handle non-OneDrive picker request
        super.onActivityResult(requestCode, resultCode, data);
    }
}

 

Udemy Generic 728x90

Spread the word. Share this post!