I have the following function to authorize access to Google Drive in order to create a folder on Google Drive using GoogleCredentials.
implementation("com.google.android.gms:play-services-auth:21.2.0")
implementation("com.google.api-client:google-api-client:2.5.0")
implementation("com.google.apis:google-api-services-drive:v3-rev20240521-2.0.0")
implementation("com.google.http-client:google-http-client-android:1.26.0")
// Google Sign in
fun signIn(context: Context) {
val authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(SCOPES).build()
Identity.getAuthorizationClient(context as Activity).authorize(authorizationRequest)
.addOnSuccessListener { authorizationResult ->
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
val pendingIntent = authorizationResult.pendingIntent
try {
startIntentSenderForResult(
context, pendingIntent!!.intentSender, 999, null, 0, 0, 0, null
)
} catch (e: IntentSender.SendIntentException) {
Log.i("@@@", "Authorization failed: " + e.message)
}
} else {
// Access authorized, do stuff
Log.i("@@@", "Access granted")
val token = authorizationResult.accessToken
val credentials = GoogleCredentials.create(AccessToken(token, null))
val requestInitializer = HttpCredentialsAdapter(credentials)
val googleDriveService = Drive.Builder(
AndroidHttp.newCompatibleTransport(), //NetHttpTransport(),
GsonFactory(), requestInitializer
)
.setApplicationName(context.getString(R.string.app_name))
.build()
Log.i("@@@", googleDriveService.toString())
try {
// Create folder on Google Drive
// Folder metadata
val folderMetadata =
File().setMimeType("application/vnd.google-apps.folder")
.setParents(listOf(ROOT))
.setName(FOLDER_NAME).setStarred(true)
.setFolderColorRgb("#FF0000") // Red color
// Create folder
googleDriveService.files().create(folderMetadata).execute() // This crashes the app, error msg: null
} catch (e: Exception) {
Log.e("@@@", e.message.toString())
}
}
}.addOnFailureListener { e -> Log.e("@@@", "Failed to authorize", e) }
}
Everything seems to be fine as far as syntax, howwever the folder is not created and after testing the following: googleDriveService.files().create(folderMetadata).execute() causes a crash the error message is “null”
I call the above function from a button’s onClick = { signIn(context) }
I would really appreciate any help with this, I’ve been strugling for weeks with this. Thanks.
MDC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.