Upload a file to a Google Drive Folder - android

I have an existing File object, created during my program. How can I use the drive API to upload this to a specific folder?
I understand it's something like this:
String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id, parents")
.execute();
System.out.println("File ID: " + file.getId());
But
How do I create the driveService object
How do I replicate the above
if I want to use a File object generated in my program, not one that
exists on my computer?

For Creating driveService(com.google.api.services.drive.Drive) class you need Google Single SignOn, And also you need to add the scope in Google console, and you need to use com.google.api.services.drive.Drive.Builder#Builder for creating the class.
For Auth process, you can refer this
For Complete Sample for Android, you can refer to this class

Related

Create a txt file using Drive API

https://developers.google.com/drive/api/v3/appdata#create_a_file_in_the_application_data_folder here is an example how to create a file using Google Drive API on the appData folder. I didn't find any example on how to create a txt file and manipulate it's content using the Google Drive API.
Any help is appreciated.
To create a txt filte in the appData folder
Modify the Name and filePath of sample code snippet in the documentation from json to txt and the mimeType from application/json to text/plain:
File fileMetadata = new File();
fileMetadata.setName("config.txt");
fileMetadata.setParents(Collections.singletonList("appDataFolder"));
java.io.File filePath = new java.io.File("files/config.txt");
FileContent mediaContent = new FileContent("text/plain", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
To manipulate the content of the file
See here for official information on how to upload the content.
Basically, for a single request you need to
obtain the resumable URI
perfom PUT request to it containing the file content in the request body
Specify the content length (mediaContent.setLength())
I do not have a Java snippet for this part, but I have done it before in Apps Script - I hope this is helpful to understand how you can manipulate the content of the file you crated in the appData fodler.
See also here for a detailed sample on how to upload a file with content in Java.

Create folder in drive with rest v2 in android app

I am trying to create a folder in Drive and using below
String folderName = UrlConstants.APP_NAME + "_dont_delete";
File fileMetadata = new File();
fileMetadata.setTitle(folderName);
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = null;
try {
file = driveService.files().insert(fileMetadata)
.setFields("id")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
However it is not creating folder in drive , instead it is creating a document named 'Untitled'.
Thanks in advance.
In Drive API for Android, note that working with folders has slight differences when compared to Google Drive API. Folders in the Drive API for Android are specialized resources within metadata and a DriveId and to create a folder, call DriveFolder.createFolder for the root folder. Then, pass the metadata containing the title and other attributes to set the values for the folder.
For a full working example, see the CreateFolderActivity sample in the Google Drive Android API Demos app.
The CloudRail SDK allows you to do that in a pretty simple way:
GoogleDrive service = new GoogleDrive(
this,
"[Google Drive Client Identifier]",
"[Google Drive Client Secret]",
"http://localhost:12345/auth",
"someState"
);
service.createFolder(
"/myFolder"
);

Adding an already created folder to Google Drive in Android

I want use google drive in my android app to backup folders that contain text, image and video files.
My problem is that while I can upload each text, image and video file separately using the Drive API, I can't see a way to upload entire folders at once so that the organisation remains intact.
The organisation of the folders is as follows:
app>Projects>notes>photos/text/video
Ideally I would like to upload the folder "app" and along with all of its contents while keeping the parent/child structure.
Are you using Google Drive Api for Android or the REST Api ?
If you are using the REST API you can create a folder like this :
private String createFolder() throws IOException {
File fileMetadata = new File();
fileMetadata.setName("FOLDER_NAME");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
String Folderid = file.getId();
And then with the file id you do this :
File nFile= new File();
nFile.setName("FILE_NAME");
nFile.setParents(Collections.singletonList(Folderid));
File file = mService.nFile().create(fileMetadata).execute();
The setParents is used to create the file INSIDE the parent which is the folder just created in this example.

mkdirs() on application internal memory fails on Android

in my app I am seeing few crashes when I try to create a directory structure under the application internal storage, such as /data/data/[pkgname]/x/y/z....
Here is the failing code:
File clusterDirectory = new File(MyApplication.getContext().getFilesDir(), "store");
File baseDirectory = new File(clusterDirectory, "data");
if (!baseDirectory.exists()) {
if (!baseDirectory.mkdirs()) {
throw new RuntimeException("Can't create the directory: " + baseDirectory);
}
}
My code is throwing the exception when trying to create the following path:
java.lang.RuntimeException: Can't create the directory: /data/data/my.app.pkgname/files/store/data
My manifest specifies the permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />, even if it should not be necessary for this purpose (it is actually necessary for my apps due to Google Maps Android API v2).
It doesn't seem to be related to the phone, since I get this exception on old phones as well as on new ones (last crash report is Nexus 4 with Android 4.3).
My guess is that the directory /data/data/my.app.pkgname doesn't exist in the first place but mkdirs() can't create it because of permissions issues, could that be possible?
Any hints?
Thanks
Use getDir(String name, int mode) to create directory into internal memory. The method Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory.
So example is
// Create directory into internal memory;
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
// Get a file myfile within the dir mydir.
File fileWithinMyDir = new File(mydir, "myfile");
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
For nested directories, you should use normal java method. Like
new File(parentDir, "childDir").mkdir();
So updated example should be
// Create directory into internal memory;
File mydir = getDir("mydir", Context.MODE_PRIVATE);
// Create sub-directory mysubdir
File mySubDir = new File(mydir, "mysubdir");
mySubDir.mkdir();
// Get a file myfile within the dir mySubDir.
File fileWithinMyDir = new File(mySubDir, "myfile");
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);

Removing "app_" prefix when creating subdirectories in application's internal storage

Android provides many options for storing data persistently on the device. I have opted for internal storage, so please don't make suggestions for storing on an SD card. (I've seen too many questions about internal storage have answers for SD cards!!)
I would like to create subdirectories in my application's internal storage directory. I followed this SO answer, reproduced below.
File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
Unfortunately, that's creating subdirectories with "app_" prefixes. So, from the example, the subdirectory looks like "app_mydir" (not ideal).
The answer to this SO question suggests that you can get rid of the "app_" prefix this way:
m_applicationDir = new File(this.getFilesDir() + "");
m_picturesDir = new File(m_applicationDir + "/mydir");
But I want to write a zip to something like /data/data/com.mypackages/files/mydir/the.zip.
So, in the end, my code looks like this:
File appDir = new File(getApplicationContext().getFilesDir() + "");
File subDir = new File(appDir + "/subDir");
File outFile = new File(subDir, "/creative.zip");
But, this is creating another error: "File does not exist" when I try this:
FileOutputStream fileStream = new FileOutputStream(outFile);
How can I (1) create a subdirectory without the "app_" prefix and (2) write a zip into it?
Also, if my first demand isn't reasonable, tell me why in the comments! I'm sure "app_" prefix has some meaning that escapes me atm.
Did you create the directories?
File appDir = getApplicationContext().getFilesDir();
File subDir = new File(appDir, "subDir");
if( !subDir.exists() )
subDir.mkdir();
File outFile = new File(subDir, "creative.zip");
Note that you shouldn't use / anywhere in your app, just in case it changes. If you do want to create your own paths, use File.separator.

Categories

Resources