conteh
conteh

Reputation: 1614

Why does google drive api create a File with a null name

I'm getting an NullPointerException from uploadedFile.getName() in the following code that utilizes the google api. If I change that to a string fileName the code works fine.

public static void downloadFile(boolean useDirectDownload, File uploadedFile, java.io.File parentDir)throws IOException {
    OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getName()));
    DRIVE.files().get(uploadedFile.getId()).executeMediaAndDownloadTo(out);
}

I understand what a null pointer is but not sure why I'm getting one in this case because prior to calling the download file I set the filename in code earlier and the file is uploaded with the name I set.

public static File uploadFile(boolean useDirectUpload, String uploadFilePath, String fileType, String fileName) throws IOException {

File fileMetadata = new File();
fileMetadata.setName(fileName);
fileMetadata.setMimeType(fileType);

java.io.File filePath = new java.io.File(uploadFilePath);
FileContent mediaContent = new FileContent(fileType, filePath);
return DRIVE.files().create(fileMetadata, mediaContent)
        .setFields("id")
        .execute();
}

The above two sets of code are called by

java.io.File parentDir = P.createDirectory("C:\\DIR");         
File uploadedFile = P.uploadFile(true, "C:\\DIR\AA.pdf", "application/pdf", "BB.pdf");
P.downloadFile(true, uploadedFile, parentDir);

For a specific question, why does the File returned by the following statement have null for the name?

return DRIVE.files().create(fileMetadata, mediaContent)
            .setFields("id")
            .execute();

Maven dependency for drive services:

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v3-rev40-1.22.0</version>
</dependency>

Upvotes: 0

Views: 435

Answers (2)

pinoyyid
pinoyyid

Reputation: 22286

why does the File returned by the following statement have null for the name?

Because you haven't requested the file name to be included in the REST response. Change .setFields("id") to .setFields("id, name")

Upvotes: 1

adjuremods
adjuremods

Reputation: 2998

You're only getting id as part of the partial response when the create method is called since its the only one specified in the setFields - https://developers.google.com/resources/api-libraries/documentation/drive/v3/java/latest/com/google/api/services/drive/Drive.Files.Create.html.

Try to add other fields (name, and other related fields necessary) and the call should work

Upvotes: 2

Related Questions