Create a File on Google Drive

suggest change

We will add a file on Google Drive. We will use the createFile() method of a Drive object to create file programmatically on Google Drive. In this example we are adding a new text file in the user’s root folder. When a file is added, we need to specify the initial set of metadata, file contents, and the parent folder.

We need to create a CreateMyFile() callback method and within this method, use the Drive object to retrieve a DriveContents resource. Then we pass the API client to the Drive object and call the driveContentsCallback callback method to handle result of DriveContents.

A DriveContents resource contains a temporary copy of the file’s binary stream which is only available to the application.

public void CreateMyFile(){
    fileOperation = true;
    // Create new contents resource.
    Drive.DriveApi.newDriveContents(mGoogleApiClient)
                  .setResultCallback(driveContentsCallback);
}

Result Handler of DriveContents

Handling the response requires to check if the call was successful or not. If the call was successful, we can retrieve the DriveContents resource.

We will create a result handler of DriveContents. Within this method, we call the CreateFileOnGoogleDrive() method and pass the result of DriveContentsResult:

/**
 * This is the Result result handler of Drive contents.
 * This callback method calls the CreateFileOnGoogleDrive() method.
 */
final ResultCallback<DriveContentsResult> driveContentsCallback =
         new ResultCallback<DriveContentsResult>() {
            @Override
            public void onResult(DriveContentsResult result) {
                if (result.getStatus().isSuccess()) {
                    if (fileOperation == true){
                        CreateFileOnGoogleDrive(result);
                    }
                }
            }
        };

Create File Programmatically

To create files, we need to use a MetadataChangeSet object. By using this object, we set the title (file name) and file type. Also, we must use the createFile() method of the DriveFolder class and pass the Google client API, the MetaDataChangeSet object, and the driveContents to create a file. We call the result handler callback to handle the result of the created file.

We use the following code to create a new text file in the user’s root folder:

/**
 * Create a file in the root folder using a MetadataChangeSet object.
 * @param result
 */
public void CreateFileOnGoogleDrive(DriveContentsResult result){

    final DriveContents driveContents = result.getDriveContents();

    // Perform I/O off the UI thread.
    new Thread() {
        @Override
        public void run() {
            // Write content to DriveContents.
            OutputStream outputStream = driveContents.getOutputStream();
            Writer writer = new OutputStreamWriter(outputStream);
            try {
                writer.write("Hello Christlin!");
                writer.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle("My First Drive File")
                    .setMimeType("text/plain")
                    .setStarred(true).build();

            // Create a file in the root folder.
            Drive.DriveApi.getRootFolder(mGoogleApiClient)
                    .createFile(mGoogleApiClient, changeSet, driveContents)
                    setResultCallback(fileCallback);
        }
   }.start();
}

Handle result of Created File

The following code will create a callback method to handle the result of the created file:

/**
 * Handle result of Created file
 */
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
        ResultCallback<DriveFolder.DriveFileResult>() {
            @Override
            public void onResult(DriveFolder.DriveFileResult result) {
                if (result.getStatus().isSuccess()) {
                    Toast.makeText(getApplicationContext(), "file created: "+
                                result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
                }
                return;
            }
        };

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Google Drive API:
* Create a File on Google Drive

Table Of Contents
2 Gradle
5 Intent
17 Service
19 WebView
31 SQLite
35 Glide
37 Dialog
38 ACRA
44 Handler
53 Toast
63 Menu
65 Picasso
70 Volley
71 Widgets
78 Realm
90 Spinner
95 OkHttp
108 TextView
109 ListView
111 Loader
118 Xposed
119 Security
121 ImageView
123 Doze Mode
130 Drawables
131 Colors
134 Fresco
139 AdMob
145 Keyboard
146 Button
150 EditText
155 Vk SDK
163 ExoPlayer
169 XMPP
175 OpenCV
177 Threads
184 ORMLite
186 TabLayout
190 LruCache
192 Zip files
194 Fastlane
199 FileIO
202 Moshi
210 VideoView
216 Paint
218 ProGuard
226 CleverTap
228 ADB shell
229 Ping ICMP
230 AIDL
234 Context
240 JCodec
242 Okio
249 FuseView
254 Looper
256 Google Drive API
261 Fastjson
263 Jackson
267 Smartcard