How to upload local file from external directory to google drive using android api?












0














I've done some progress with the Google Drive API, I can create files and folders. However, I cannot seem to figure out how to upload a folder from device storage to google drive, or how to create folders or files inside Drive Folders.
I also want to know how to retrieve files inside any given Drive Folder.
I would much appreciate a detailed explanation with examples and not a link to the official documentation as I have been struggling with it for days (And I Know I'm Not The Only One).



Here's the code I've gotten so far.



public abstract class DriveActivity extends UtilsActivity {

private static final int REQUEST_CODE_SIGN_IN = 77;
public static final String PIONEER_DRIVE_ROOT_FOLDER = "Pioneer Backups ID_77";
public FileManagerHelper mFileManagerHelper;
private GoogleSignInClient mGoogleSignInClient;
private DriveClient mDriveClient;
public OptionsClass mOptionsClass;


/**
* Inits file manager and Google Sign In Client
*/
protected void Init() {

mFileManagerHelper = new FileManagerHelper(this);
mOptionsClass = new OptionsClass(getApplicationContext());

mGoogleSignInClient = buildSignInOptions();


if (loggedIntoGoogleDrive() && mOptionsClass.getEnableDrive()) {

/*
Create the main pioneer folder, where all the backups will be stored.
*/
//TODO heck if the folder already exists
// createFolder(getRootFolderTask(),
// new MetadataChangeSet.Builder()
// .setTitle(PIONEER_DRIVE_ROOT_FOLDER)
// .setDescription("Root Folder For All Pioneer Backups")
// .build(), false);

}

}

/**
* Sign user out of google account
*/
public void signOutOfGoogleDrive() {
onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
mGoogleSignInClient
.signOut()
/*
Success
*/
.addOnSuccessListener(aVoid -> {
onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
Toast.makeText(DriveActivity.this, "Signed Out", Toast.LENGTH_SHORT).show();
})
/*
Failure
*/
.addOnFailureListener(e -> {
onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
e.printStackTrace();
Toast.makeText(DriveActivity.this, "Failure " + e.getMessage(), Toast.LENGTH_SHORT).show();
})
/*
Completion
*/
.addOnCompleteListener(task -> {
onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
Toast.makeText(DriveActivity.this, "Done", Toast.LENGTH_SHORT).show();
});
}

/**
* Get user data, to enable Google Drive
*
* @return ResourceClient
*/
public DriveResourceClient getDriveResourceClient() {
return Drive.getDriveResourceClient(getApplicationContext(), getGoogleAccount());
}

public boolean loggedIntoGoogleDrive() {
return getGoogleAccount() != null;
}

/**
* @return the las logged in account
*/
public GoogleSignInAccount getGoogleAccount() {
return GoogleSignIn.getLastSignedInAccount(this);
}

/**
* @return the scopes the user needs to grant to the app
*/
private Set<Scope> getRequiredScopes() {
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
return requiredScopes;
}

/**
* Start sign in activity.
*/
public void signInToGoogleDrive() {
onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
/*
Check if we have all the required scopes and if the user if logged in
*/
if (loggedIntoGoogleDrive() && getGoogleAccount().getGrantedScopes().containsAll(getRequiredScopes())) {

initializeDriveClient(getGoogleAccount());

onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);

} else {

GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();

GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}

startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);


}

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

super.onActivityResult(requestCode, resultCode, data);

if (resultCode == REQUEST_CODE_SIGN_IN) {
onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
}

}

public void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

mDriveClient.getUploadPreferences().addOnSuccessListener(transferPreferences -> {

});
}

/**
* Build a Google SignIn client.
*/
private GoogleSignInClient buildSignInOptions() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
return GoogleSignIn.getClient(this, signInOptions);
}

/**
* Uploads a file to drive
*
* @param file to upload
*/
public void uploadFileToDrive(File file, String des) {

if (!loggedIntoGoogleDrive()) {
signInToGoogleDrive();
return;
} else if (!mOptionsClass.getEnableDrive()) {
makeText("Enable Drive Backup First");
}


// getRootFolderTask()
// .continueWithTask(task -> {
//
// DriveFolder parentFolder = task.getResult();
//
// String fileName = file.getName();
//
// String from = file.getAbsolutePath();
//
// String fileDes =
// "Pioneer Backup File. Uploaded: " + CalendarHelper.getSimpleFormattedDateAndTime(true);
//
// MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
// .setTitle(fileName)
// .setMimeType("text/plain")
// .setDescription(fileDes + "_" + from)
// .setStarred(true)
// .build();
//
// return getDriveResourceClient().createFile(parentFolder, changeSet, null);
// })
// .addOnSuccessListener(this,
// driveFile -> {
// Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
// })
// .addOnFailureListener(this, e -> {
// Toast.makeText(this, "Error " + e.getMessage(), Toast.LENGTH_SHORT).show();
// });
}

private Task<DriveFolder> getRootFolderTask() {
return getDriveResourceClient().getRootFolder();
}

/**
* Creates a file inside a folder
*/
private void createFile(@NonNull Task<DriveFolder> folderToGoIn, String name) {

addTaskListenerToDriveFolder(folderToGoIn.continueWithTask(task -> {
if (task.getResult() != null) {
DriveFolder parentFolder = task.getResult();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(name)
.setMimeType("text/plain")
.setStarred(true)
.build();
return getDriveResourceClient().createFolder(parentFolder, changeSet);
} else {
makeText("Error");
return null;
}

}), false);
}

private void createFolder(@NonNull Task<DriveFolder> folderToGoIn, MetadataChangeSet folderMetadata, boolean notify) {
addTaskListenerToDriveFolder(folderToGoIn
.continueWithTask(task -> {
if (task.getResult() != null) {
DriveFolder parentFolder = task.getResult();
return getDriveResourceClient().createFolder(parentFolder, folderMetadata);
} else {
makeText("Error");
return null;
}
}), notify);
}

private Task<DriveContents> readFile(DriveFile file) {
return getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
}


private Task<MetadataBuffer> getFoldersIn(DriveFolder driveFolder) {

Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE))
.build();


return getDriveResourceClient().queryChildren(driveFolder, query);

}

public List<File> getDriveBackups() {
//TODO get actual files inside the backup folder
return getLocalBackups();
}


public void viewDriveBackups() {
/*
Open the Google Drive app to view the backups folder
*/
}

/**
* Adds task failure, success, complete and cancelled listeners.
* Automatically notifies the user of state
*
* @param task to add listeners
*/
private void addTaskListenerToDriveFolder(Task<DriveFolder> task, boolean notify) {
onProcessStart(PROCESS_KEY_BACKUP_RELATED);
task
.addOnCanceledListener(() -> {
onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
if (notify)
makeText("Cancelled");

})
.addOnCompleteListener(task1 -> {
onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
if (notify)
makeText("Completed");
})
.addOnSuccessListener(driveFolder -> {
onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
if (notify)
makeText("Success");
})
.addOnFailureListener(this, e -> {
onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
if (notify)
makeText("Error " + e.getMessage());
});
}


}









share|improve this question





























    0














    I've done some progress with the Google Drive API, I can create files and folders. However, I cannot seem to figure out how to upload a folder from device storage to google drive, or how to create folders or files inside Drive Folders.
    I also want to know how to retrieve files inside any given Drive Folder.
    I would much appreciate a detailed explanation with examples and not a link to the official documentation as I have been struggling with it for days (And I Know I'm Not The Only One).



    Here's the code I've gotten so far.



    public abstract class DriveActivity extends UtilsActivity {

    private static final int REQUEST_CODE_SIGN_IN = 77;
    public static final String PIONEER_DRIVE_ROOT_FOLDER = "Pioneer Backups ID_77";
    public FileManagerHelper mFileManagerHelper;
    private GoogleSignInClient mGoogleSignInClient;
    private DriveClient mDriveClient;
    public OptionsClass mOptionsClass;


    /**
    * Inits file manager and Google Sign In Client
    */
    protected void Init() {

    mFileManagerHelper = new FileManagerHelper(this);
    mOptionsClass = new OptionsClass(getApplicationContext());

    mGoogleSignInClient = buildSignInOptions();


    if (loggedIntoGoogleDrive() && mOptionsClass.getEnableDrive()) {

    /*
    Create the main pioneer folder, where all the backups will be stored.
    */
    //TODO heck if the folder already exists
    // createFolder(getRootFolderTask(),
    // new MetadataChangeSet.Builder()
    // .setTitle(PIONEER_DRIVE_ROOT_FOLDER)
    // .setDescription("Root Folder For All Pioneer Backups")
    // .build(), false);

    }

    }

    /**
    * Sign user out of google account
    */
    public void signOutOfGoogleDrive() {
    onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
    mGoogleSignInClient
    .signOut()
    /*
    Success
    */
    .addOnSuccessListener(aVoid -> {
    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
    Toast.makeText(DriveActivity.this, "Signed Out", Toast.LENGTH_SHORT).show();
    })
    /*
    Failure
    */
    .addOnFailureListener(e -> {
    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
    e.printStackTrace();
    Toast.makeText(DriveActivity.this, "Failure " + e.getMessage(), Toast.LENGTH_SHORT).show();
    })
    /*
    Completion
    */
    .addOnCompleteListener(task -> {
    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
    Toast.makeText(DriveActivity.this, "Done", Toast.LENGTH_SHORT).show();
    });
    }

    /**
    * Get user data, to enable Google Drive
    *
    * @return ResourceClient
    */
    public DriveResourceClient getDriveResourceClient() {
    return Drive.getDriveResourceClient(getApplicationContext(), getGoogleAccount());
    }

    public boolean loggedIntoGoogleDrive() {
    return getGoogleAccount() != null;
    }

    /**
    * @return the las logged in account
    */
    public GoogleSignInAccount getGoogleAccount() {
    return GoogleSignIn.getLastSignedInAccount(this);
    }

    /**
    * @return the scopes the user needs to grant to the app
    */
    private Set<Scope> getRequiredScopes() {
    Set<Scope> requiredScopes = new HashSet<>(2);
    requiredScopes.add(Drive.SCOPE_FILE);
    requiredScopes.add(Drive.SCOPE_APPFOLDER);
    return requiredScopes;
    }

    /**
    * Start sign in activity.
    */
    public void signInToGoogleDrive() {
    onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
    /*
    Check if we have all the required scopes and if the user if logged in
    */
    if (loggedIntoGoogleDrive() && getGoogleAccount().getGrantedScopes().containsAll(getRequiredScopes())) {

    initializeDriveClient(getGoogleAccount());

    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);

    } else {

    GoogleSignInOptions signInOptions =
    new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
    .requestScopes(Drive.SCOPE_FILE)
    .requestScopes(Drive.SCOPE_APPFOLDER)
    .build();

    GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
    startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
    }

    startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);


    }

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

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == REQUEST_CODE_SIGN_IN) {
    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
    }

    }

    public void initializeDriveClient(GoogleSignInAccount signInAccount) {
    mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

    mDriveClient.getUploadPreferences().addOnSuccessListener(transferPreferences -> {

    });
    }

    /**
    * Build a Google SignIn client.
    */
    private GoogleSignInClient buildSignInOptions() {
    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
    .requestScopes(Drive.SCOPE_FILE)
    .requestScopes(Drive.SCOPE_APPFOLDER)
    .build();
    return GoogleSignIn.getClient(this, signInOptions);
    }

    /**
    * Uploads a file to drive
    *
    * @param file to upload
    */
    public void uploadFileToDrive(File file, String des) {

    if (!loggedIntoGoogleDrive()) {
    signInToGoogleDrive();
    return;
    } else if (!mOptionsClass.getEnableDrive()) {
    makeText("Enable Drive Backup First");
    }


    // getRootFolderTask()
    // .continueWithTask(task -> {
    //
    // DriveFolder parentFolder = task.getResult();
    //
    // String fileName = file.getName();
    //
    // String from = file.getAbsolutePath();
    //
    // String fileDes =
    // "Pioneer Backup File. Uploaded: " + CalendarHelper.getSimpleFormattedDateAndTime(true);
    //
    // MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
    // .setTitle(fileName)
    // .setMimeType("text/plain")
    // .setDescription(fileDes + "_" + from)
    // .setStarred(true)
    // .build();
    //
    // return getDriveResourceClient().createFile(parentFolder, changeSet, null);
    // })
    // .addOnSuccessListener(this,
    // driveFile -> {
    // Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
    // })
    // .addOnFailureListener(this, e -> {
    // Toast.makeText(this, "Error " + e.getMessage(), Toast.LENGTH_SHORT).show();
    // });
    }

    private Task<DriveFolder> getRootFolderTask() {
    return getDriveResourceClient().getRootFolder();
    }

    /**
    * Creates a file inside a folder
    */
    private void createFile(@NonNull Task<DriveFolder> folderToGoIn, String name) {

    addTaskListenerToDriveFolder(folderToGoIn.continueWithTask(task -> {
    if (task.getResult() != null) {
    DriveFolder parentFolder = task.getResult();
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
    .setTitle(name)
    .setMimeType("text/plain")
    .setStarred(true)
    .build();
    return getDriveResourceClient().createFolder(parentFolder, changeSet);
    } else {
    makeText("Error");
    return null;
    }

    }), false);
    }

    private void createFolder(@NonNull Task<DriveFolder> folderToGoIn, MetadataChangeSet folderMetadata, boolean notify) {
    addTaskListenerToDriveFolder(folderToGoIn
    .continueWithTask(task -> {
    if (task.getResult() != null) {
    DriveFolder parentFolder = task.getResult();
    return getDriveResourceClient().createFolder(parentFolder, folderMetadata);
    } else {
    makeText("Error");
    return null;
    }
    }), notify);
    }

    private Task<DriveContents> readFile(DriveFile file) {
    return getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
    }


    private Task<MetadataBuffer> getFoldersIn(DriveFolder driveFolder) {

    Query query = new Query.Builder()
    .addFilter(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE))
    .build();


    return getDriveResourceClient().queryChildren(driveFolder, query);

    }

    public List<File> getDriveBackups() {
    //TODO get actual files inside the backup folder
    return getLocalBackups();
    }


    public void viewDriveBackups() {
    /*
    Open the Google Drive app to view the backups folder
    */
    }

    /**
    * Adds task failure, success, complete and cancelled listeners.
    * Automatically notifies the user of state
    *
    * @param task to add listeners
    */
    private void addTaskListenerToDriveFolder(Task<DriveFolder> task, boolean notify) {
    onProcessStart(PROCESS_KEY_BACKUP_RELATED);
    task
    .addOnCanceledListener(() -> {
    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
    if (notify)
    makeText("Cancelled");

    })
    .addOnCompleteListener(task1 -> {
    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
    if (notify)
    makeText("Completed");
    })
    .addOnSuccessListener(driveFolder -> {
    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
    if (notify)
    makeText("Success");
    })
    .addOnFailureListener(this, e -> {
    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
    if (notify)
    makeText("Error " + e.getMessage());
    });
    }


    }









    share|improve this question



























      0












      0








      0







      I've done some progress with the Google Drive API, I can create files and folders. However, I cannot seem to figure out how to upload a folder from device storage to google drive, or how to create folders or files inside Drive Folders.
      I also want to know how to retrieve files inside any given Drive Folder.
      I would much appreciate a detailed explanation with examples and not a link to the official documentation as I have been struggling with it for days (And I Know I'm Not The Only One).



      Here's the code I've gotten so far.



      public abstract class DriveActivity extends UtilsActivity {

      private static final int REQUEST_CODE_SIGN_IN = 77;
      public static final String PIONEER_DRIVE_ROOT_FOLDER = "Pioneer Backups ID_77";
      public FileManagerHelper mFileManagerHelper;
      private GoogleSignInClient mGoogleSignInClient;
      private DriveClient mDriveClient;
      public OptionsClass mOptionsClass;


      /**
      * Inits file manager and Google Sign In Client
      */
      protected void Init() {

      mFileManagerHelper = new FileManagerHelper(this);
      mOptionsClass = new OptionsClass(getApplicationContext());

      mGoogleSignInClient = buildSignInOptions();


      if (loggedIntoGoogleDrive() && mOptionsClass.getEnableDrive()) {

      /*
      Create the main pioneer folder, where all the backups will be stored.
      */
      //TODO heck if the folder already exists
      // createFolder(getRootFolderTask(),
      // new MetadataChangeSet.Builder()
      // .setTitle(PIONEER_DRIVE_ROOT_FOLDER)
      // .setDescription("Root Folder For All Pioneer Backups")
      // .build(), false);

      }

      }

      /**
      * Sign user out of google account
      */
      public void signOutOfGoogleDrive() {
      onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
      mGoogleSignInClient
      .signOut()
      /*
      Success
      */
      .addOnSuccessListener(aVoid -> {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      Toast.makeText(DriveActivity.this, "Signed Out", Toast.LENGTH_SHORT).show();
      })
      /*
      Failure
      */
      .addOnFailureListener(e -> {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      e.printStackTrace();
      Toast.makeText(DriveActivity.this, "Failure " + e.getMessage(), Toast.LENGTH_SHORT).show();
      })
      /*
      Completion
      */
      .addOnCompleteListener(task -> {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      Toast.makeText(DriveActivity.this, "Done", Toast.LENGTH_SHORT).show();
      });
      }

      /**
      * Get user data, to enable Google Drive
      *
      * @return ResourceClient
      */
      public DriveResourceClient getDriveResourceClient() {
      return Drive.getDriveResourceClient(getApplicationContext(), getGoogleAccount());
      }

      public boolean loggedIntoGoogleDrive() {
      return getGoogleAccount() != null;
      }

      /**
      * @return the las logged in account
      */
      public GoogleSignInAccount getGoogleAccount() {
      return GoogleSignIn.getLastSignedInAccount(this);
      }

      /**
      * @return the scopes the user needs to grant to the app
      */
      private Set<Scope> getRequiredScopes() {
      Set<Scope> requiredScopes = new HashSet<>(2);
      requiredScopes.add(Drive.SCOPE_FILE);
      requiredScopes.add(Drive.SCOPE_APPFOLDER);
      return requiredScopes;
      }

      /**
      * Start sign in activity.
      */
      public void signInToGoogleDrive() {
      onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
      /*
      Check if we have all the required scopes and if the user if logged in
      */
      if (loggedIntoGoogleDrive() && getGoogleAccount().getGrantedScopes().containsAll(getRequiredScopes())) {

      initializeDriveClient(getGoogleAccount());

      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);

      } else {

      GoogleSignInOptions signInOptions =
      new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
      .requestScopes(Drive.SCOPE_FILE)
      .requestScopes(Drive.SCOPE_APPFOLDER)
      .build();

      GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
      startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
      }

      startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);


      }

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

      super.onActivityResult(requestCode, resultCode, data);

      if (resultCode == REQUEST_CODE_SIGN_IN) {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      }

      }

      public void initializeDriveClient(GoogleSignInAccount signInAccount) {
      mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

      mDriveClient.getUploadPreferences().addOnSuccessListener(transferPreferences -> {

      });
      }

      /**
      * Build a Google SignIn client.
      */
      private GoogleSignInClient buildSignInOptions() {
      GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
      .requestScopes(Drive.SCOPE_FILE)
      .requestScopes(Drive.SCOPE_APPFOLDER)
      .build();
      return GoogleSignIn.getClient(this, signInOptions);
      }

      /**
      * Uploads a file to drive
      *
      * @param file to upload
      */
      public void uploadFileToDrive(File file, String des) {

      if (!loggedIntoGoogleDrive()) {
      signInToGoogleDrive();
      return;
      } else if (!mOptionsClass.getEnableDrive()) {
      makeText("Enable Drive Backup First");
      }


      // getRootFolderTask()
      // .continueWithTask(task -> {
      //
      // DriveFolder parentFolder = task.getResult();
      //
      // String fileName = file.getName();
      //
      // String from = file.getAbsolutePath();
      //
      // String fileDes =
      // "Pioneer Backup File. Uploaded: " + CalendarHelper.getSimpleFormattedDateAndTime(true);
      //
      // MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
      // .setTitle(fileName)
      // .setMimeType("text/plain")
      // .setDescription(fileDes + "_" + from)
      // .setStarred(true)
      // .build();
      //
      // return getDriveResourceClient().createFile(parentFolder, changeSet, null);
      // })
      // .addOnSuccessListener(this,
      // driveFile -> {
      // Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
      // })
      // .addOnFailureListener(this, e -> {
      // Toast.makeText(this, "Error " + e.getMessage(), Toast.LENGTH_SHORT).show();
      // });
      }

      private Task<DriveFolder> getRootFolderTask() {
      return getDriveResourceClient().getRootFolder();
      }

      /**
      * Creates a file inside a folder
      */
      private void createFile(@NonNull Task<DriveFolder> folderToGoIn, String name) {

      addTaskListenerToDriveFolder(folderToGoIn.continueWithTask(task -> {
      if (task.getResult() != null) {
      DriveFolder parentFolder = task.getResult();
      MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
      .setTitle(name)
      .setMimeType("text/plain")
      .setStarred(true)
      .build();
      return getDriveResourceClient().createFolder(parentFolder, changeSet);
      } else {
      makeText("Error");
      return null;
      }

      }), false);
      }

      private void createFolder(@NonNull Task<DriveFolder> folderToGoIn, MetadataChangeSet folderMetadata, boolean notify) {
      addTaskListenerToDriveFolder(folderToGoIn
      .continueWithTask(task -> {
      if (task.getResult() != null) {
      DriveFolder parentFolder = task.getResult();
      return getDriveResourceClient().createFolder(parentFolder, folderMetadata);
      } else {
      makeText("Error");
      return null;
      }
      }), notify);
      }

      private Task<DriveContents> readFile(DriveFile file) {
      return getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
      }


      private Task<MetadataBuffer> getFoldersIn(DriveFolder driveFolder) {

      Query query = new Query.Builder()
      .addFilter(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE))
      .build();


      return getDriveResourceClient().queryChildren(driveFolder, query);

      }

      public List<File> getDriveBackups() {
      //TODO get actual files inside the backup folder
      return getLocalBackups();
      }


      public void viewDriveBackups() {
      /*
      Open the Google Drive app to view the backups folder
      */
      }

      /**
      * Adds task failure, success, complete and cancelled listeners.
      * Automatically notifies the user of state
      *
      * @param task to add listeners
      */
      private void addTaskListenerToDriveFolder(Task<DriveFolder> task, boolean notify) {
      onProcessStart(PROCESS_KEY_BACKUP_RELATED);
      task
      .addOnCanceledListener(() -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Cancelled");

      })
      .addOnCompleteListener(task1 -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Completed");
      })
      .addOnSuccessListener(driveFolder -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Success");
      })
      .addOnFailureListener(this, e -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Error " + e.getMessage());
      });
      }


      }









      share|improve this question















      I've done some progress with the Google Drive API, I can create files and folders. However, I cannot seem to figure out how to upload a folder from device storage to google drive, or how to create folders or files inside Drive Folders.
      I also want to know how to retrieve files inside any given Drive Folder.
      I would much appreciate a detailed explanation with examples and not a link to the official documentation as I have been struggling with it for days (And I Know I'm Not The Only One).



      Here's the code I've gotten so far.



      public abstract class DriveActivity extends UtilsActivity {

      private static final int REQUEST_CODE_SIGN_IN = 77;
      public static final String PIONEER_DRIVE_ROOT_FOLDER = "Pioneer Backups ID_77";
      public FileManagerHelper mFileManagerHelper;
      private GoogleSignInClient mGoogleSignInClient;
      private DriveClient mDriveClient;
      public OptionsClass mOptionsClass;


      /**
      * Inits file manager and Google Sign In Client
      */
      protected void Init() {

      mFileManagerHelper = new FileManagerHelper(this);
      mOptionsClass = new OptionsClass(getApplicationContext());

      mGoogleSignInClient = buildSignInOptions();


      if (loggedIntoGoogleDrive() && mOptionsClass.getEnableDrive()) {

      /*
      Create the main pioneer folder, where all the backups will be stored.
      */
      //TODO heck if the folder already exists
      // createFolder(getRootFolderTask(),
      // new MetadataChangeSet.Builder()
      // .setTitle(PIONEER_DRIVE_ROOT_FOLDER)
      // .setDescription("Root Folder For All Pioneer Backups")
      // .build(), false);

      }

      }

      /**
      * Sign user out of google account
      */
      public void signOutOfGoogleDrive() {
      onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
      mGoogleSignInClient
      .signOut()
      /*
      Success
      */
      .addOnSuccessListener(aVoid -> {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      Toast.makeText(DriveActivity.this, "Signed Out", Toast.LENGTH_SHORT).show();
      })
      /*
      Failure
      */
      .addOnFailureListener(e -> {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      e.printStackTrace();
      Toast.makeText(DriveActivity.this, "Failure " + e.getMessage(), Toast.LENGTH_SHORT).show();
      })
      /*
      Completion
      */
      .addOnCompleteListener(task -> {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      Toast.makeText(DriveActivity.this, "Done", Toast.LENGTH_SHORT).show();
      });
      }

      /**
      * Get user data, to enable Google Drive
      *
      * @return ResourceClient
      */
      public DriveResourceClient getDriveResourceClient() {
      return Drive.getDriveResourceClient(getApplicationContext(), getGoogleAccount());
      }

      public boolean loggedIntoGoogleDrive() {
      return getGoogleAccount() != null;
      }

      /**
      * @return the las logged in account
      */
      public GoogleSignInAccount getGoogleAccount() {
      return GoogleSignIn.getLastSignedInAccount(this);
      }

      /**
      * @return the scopes the user needs to grant to the app
      */
      private Set<Scope> getRequiredScopes() {
      Set<Scope> requiredScopes = new HashSet<>(2);
      requiredScopes.add(Drive.SCOPE_FILE);
      requiredScopes.add(Drive.SCOPE_APPFOLDER);
      return requiredScopes;
      }

      /**
      * Start sign in activity.
      */
      public void signInToGoogleDrive() {
      onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
      /*
      Check if we have all the required scopes and if the user if logged in
      */
      if (loggedIntoGoogleDrive() && getGoogleAccount().getGrantedScopes().containsAll(getRequiredScopes())) {

      initializeDriveClient(getGoogleAccount());

      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);

      } else {

      GoogleSignInOptions signInOptions =
      new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
      .requestScopes(Drive.SCOPE_FILE)
      .requestScopes(Drive.SCOPE_APPFOLDER)
      .build();

      GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
      startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
      }

      startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);


      }

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

      super.onActivityResult(requestCode, resultCode, data);

      if (resultCode == REQUEST_CODE_SIGN_IN) {
      onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
      }

      }

      public void initializeDriveClient(GoogleSignInAccount signInAccount) {
      mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

      mDriveClient.getUploadPreferences().addOnSuccessListener(transferPreferences -> {

      });
      }

      /**
      * Build a Google SignIn client.
      */
      private GoogleSignInClient buildSignInOptions() {
      GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
      .requestScopes(Drive.SCOPE_FILE)
      .requestScopes(Drive.SCOPE_APPFOLDER)
      .build();
      return GoogleSignIn.getClient(this, signInOptions);
      }

      /**
      * Uploads a file to drive
      *
      * @param file to upload
      */
      public void uploadFileToDrive(File file, String des) {

      if (!loggedIntoGoogleDrive()) {
      signInToGoogleDrive();
      return;
      } else if (!mOptionsClass.getEnableDrive()) {
      makeText("Enable Drive Backup First");
      }


      // getRootFolderTask()
      // .continueWithTask(task -> {
      //
      // DriveFolder parentFolder = task.getResult();
      //
      // String fileName = file.getName();
      //
      // String from = file.getAbsolutePath();
      //
      // String fileDes =
      // "Pioneer Backup File. Uploaded: " + CalendarHelper.getSimpleFormattedDateAndTime(true);
      //
      // MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
      // .setTitle(fileName)
      // .setMimeType("text/plain")
      // .setDescription(fileDes + "_" + from)
      // .setStarred(true)
      // .build();
      //
      // return getDriveResourceClient().createFile(parentFolder, changeSet, null);
      // })
      // .addOnSuccessListener(this,
      // driveFile -> {
      // Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
      // })
      // .addOnFailureListener(this, e -> {
      // Toast.makeText(this, "Error " + e.getMessage(), Toast.LENGTH_SHORT).show();
      // });
      }

      private Task<DriveFolder> getRootFolderTask() {
      return getDriveResourceClient().getRootFolder();
      }

      /**
      * Creates a file inside a folder
      */
      private void createFile(@NonNull Task<DriveFolder> folderToGoIn, String name) {

      addTaskListenerToDriveFolder(folderToGoIn.continueWithTask(task -> {
      if (task.getResult() != null) {
      DriveFolder parentFolder = task.getResult();
      MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
      .setTitle(name)
      .setMimeType("text/plain")
      .setStarred(true)
      .build();
      return getDriveResourceClient().createFolder(parentFolder, changeSet);
      } else {
      makeText("Error");
      return null;
      }

      }), false);
      }

      private void createFolder(@NonNull Task<DriveFolder> folderToGoIn, MetadataChangeSet folderMetadata, boolean notify) {
      addTaskListenerToDriveFolder(folderToGoIn
      .continueWithTask(task -> {
      if (task.getResult() != null) {
      DriveFolder parentFolder = task.getResult();
      return getDriveResourceClient().createFolder(parentFolder, folderMetadata);
      } else {
      makeText("Error");
      return null;
      }
      }), notify);
      }

      private Task<DriveContents> readFile(DriveFile file) {
      return getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
      }


      private Task<MetadataBuffer> getFoldersIn(DriveFolder driveFolder) {

      Query query = new Query.Builder()
      .addFilter(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE))
      .build();


      return getDriveResourceClient().queryChildren(driveFolder, query);

      }

      public List<File> getDriveBackups() {
      //TODO get actual files inside the backup folder
      return getLocalBackups();
      }


      public void viewDriveBackups() {
      /*
      Open the Google Drive app to view the backups folder
      */
      }

      /**
      * Adds task failure, success, complete and cancelled listeners.
      * Automatically notifies the user of state
      *
      * @param task to add listeners
      */
      private void addTaskListenerToDriveFolder(Task<DriveFolder> task, boolean notify) {
      onProcessStart(PROCESS_KEY_BACKUP_RELATED);
      task
      .addOnCanceledListener(() -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Cancelled");

      })
      .addOnCompleteListener(task1 -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Completed");
      })
      .addOnSuccessListener(driveFolder -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Success");
      })
      .addOnFailureListener(this, e -> {
      onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
      if (notify)
      makeText("Error " + e.getMessage());
      });
      }


      }






      java android drive






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 22:12







      MicroRJ

















      asked Nov 23 '18 at 21:00









      MicroRJMicroRJ

      314




      314
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452889%2fhow-to-upload-local-file-from-external-directory-to-google-drive-using-android-a%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452889%2fhow-to-upload-local-file-from-external-directory-to-google-drive-using-android-a%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Lallio

          Unable to find Lightning Node

          Futebolista