I'm currently trying to create a new Google Spreadsheet file using the Google Drive Android API. At the moment, this is the content of my ResultCallback class:
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
// Handle error
return;
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("My Spreadsheet")
.setMimeType("application/vnd.google-apps.spreadsheet").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, result.getContents())
.setResultCallback(fileCallback);
}
Every time I run the app I get the warning log "Upload failed HTTP status 400". However, if I change the MIME type to any non-Google service (eg. text/plain, application/vnd.ms-excel, etc.), the file is created successfully. Is this happening because I cannot create empty Google Docs files using the API?
Thank you.
Maybe the problem is that you are trying to upload Google spreadsheet without any body? Or maybe you should try to achieve what you want with pure Java SDK API?
Here is few links:
How do I upload file to google drive from android
https://developers.google.com/drive/android/create-file
I am also analyzing possibilities of integration Android client with Google Drive and apparently there is a way but not using the Drive API but Google Spreadsheets API directly to create and modify Google Spreadsheets.
Check this question
Related
I am new to Google API. By following the official Google API sample (https://developers.google.com/android/guides/api-client?authuser=0), I tried to create a DriveResourceClient object to connect my app with Google Drive. Unfortunately, I found that DriveResourceClient is deprecated. I wonder if the official guide I am reading is the latest version or not. If not, is there any latest Google API guide I can rely on? The guide I am currently reading was last updated on March 13, 2019.
Thanks.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
// Get the app's Drive folder
DriveResourceClient client = Drive.getDriveResourceClient(this,account);
client.getAppFolder().addOnCompleteListener(this, new OnCompleteListener<DriveFolder>() {
#Override
public void onComplete(#NonNull Task<DriveFolder>() {
// ...
}
});
Check out this
This is the Drive REST API.
Download by link: https://github.com/gsuitedevs/android-samples.git
Open project "deprecation". This example will help access account and download files by SAF. If you received your application credentials in the developer console: https://console.cloud.google.com
I'm trying to use the YouTubeData API with OAuth 2.0 authentication on Android, and i'm kind of struggling with it.
I've searched a lot online, but there's not much help for the Android implementation.
First of all, it's not clear to me what's the best way to obtain an OAuth token. In the doc they suggest that for Android is better to obtain it using the Google Play services lib. Is that true? if yes, it should be pretty trivial following this guide: https://developers.google.com/android/guides/http-auth.
But at this point i will have the token in a String object .. how should I use it with the YouTubeData API? Should I place it somewhere in the YouTube.Builder ?
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("AppName").build();
if yes, does anyone know where?
Searching on StackOverflow i've come across this question: What to do after getting Auth Token - Android Youtube API. Here Ibrahim Ulukaya says it's better to use GoogleAccountCredential. For what i've understood (Access to Google API - GoogleAccountCredential.usingOAuth2 vs GoogleAuthUtil.getToken()) the Android version of GoogleAccountCredential should use the GoogleAuthUtil provided from the Google Play services lib, so it could be pretty useful to simplify the process. I've looked at the sample project suggested from Ibrahim Ulukaya (https://github.com/youtube/yt-direct-lite-android) and i've implemented everything as he does. But it doesn't seem to work very well as i'm only obtaining this message in the logcat: "There was an IO error: com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission : null".
(Note that I've enabled all the required APIs on the Google Console, and created the Client ID for my app)
At this point i'm kind of lost.
Should I use directly the GoogleAuthUtil from the Google Play services lib? in this case once obtained the token as a String how can i use it with the YouTubeData APIs?
Or should I use the GoogleAccountCredential ? in this case someone knows how can I solve the "NeedPersmission : null" error?
---- EDIT:
details on what my app is trying to do: being this my first experience with this kind of APIs I started from the easy stuff: retrieve video information and then play those videos, without any user authentication. I managed to do that pretty easily, but for my app's purpose i need to access the user data, in particular users must be able to like and comment videos.
So I started implementing OAuth2, trying to do the same exact queries I was doing before (retrieve video info).
Wow. The documentation on this is super confusing. Full disclosure, I'm not an Android developer but I am a Java developer who has worked with Google apps and OAuth2.
Google Play or not Google Play? First off, Google Play Services will only be available on Android devices with Google Play Services installed (so not OUYA, Amazon devices, etc.). Google state that "the Google Play library will give you the best possible performance and experience.".
There are numerous discussions (e.g. here, here) from actual Android developers that list the various merits of Google Play verses other techniques. I would imagine that once you are able to get your application working using one method, then it should be an easy enough to change if you so desire.
Much of the example code about uses the Android AccountManager (Tasks and Calendars being favourite examples) so that is what I will show.
Your example code looks like it might be for a simple search, I would guess that many of the YouTube API interactions do not require OAuth2, in other code I've seen this empty HttpRequestInitializer implementation referred to as a no-op function. (e.g. GeolocationSearch.java).
It sounds like you want access to YouTube API operations that need account credentials. You can do something similar to this Android Calendar example (CalendarSampleActivity.java) except with YouTube, like the example answer from here.
// Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, YouTubeScopes.YOUTUBE, YouTubeScopes.YOUTUBE_READONLY);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// YouTube client
service =
new com.google.api.services.youtube.YouTube.Builder(transport, jsonFactory, credential)
.setApplicationName("Google-YouTubeAndroidSample/1.0").build();
I hope this helps.
In the initialize method of the HttpRequestInitializer you can set headers of the request. According to Googles documention for Oath2 for devices https://developers.google.com/identity/protocols/OAuth2ForDevices if you have an access token you should put it in the Authorization: Bearer HTTP header.
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
request.put("Authorization", "Bearer " + yourAccessTokenString);
}
}).setApplicationName("AppName").build();
Remember the space after the Bearer in the authorization header value
I am making a notepad app using Google Drive. Whenever user creates a file in the app, it also creates a file in the Google Drive. And user can enter the text and save the file, the unsaved text will get committed whenever the internet is available. I am managing the update and create processes within the app using the DriveId.
If the user wants to use the files with the alternative device using my app, for that I also have the option called DriveId import. By clicking the option DriveId import user will be prompted with the input box for entering the existing DriveId. Using the DriveId I thought of opening the files, But it was giving an error.
Then I saw an answer given in this SO which clearly says DriveId can be used only inside the app and device which created the file.
I also found a similar question like mine in here SO But I can’t get my problem solved. I have taken ResourceId using result.getDriveFolder().getDriveId().getResourceId()
How to read the data’s programmatically using the ResourceID? As said in the above answer here I don’t want to change the track and go into Drive REST API. Is there a way that I can read the data using Google Drive Android API ? I have done all the development process, but in the ending when I try to access from other device it is giving the error. Totally struck.
If I can only read the data using REST API any simple code will be appreciated. Thanks in advance.
Finally Solved the DriveId Issue without REST API.
To get DriveId on the alternative device. You will need resourceId. You can use following code:-
String resourseId = "xxxxxxxxxxxxx"
Drive.DriveApi.fetchDriveId(mGoogleApiClient,resourseId).setResultCallback(idCallBack);
private ResultCallBack<DriveApi.DriveResult> idCallBack = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult driveIdResult) {
msg.Log("onResult");
DriveId id = driveIdResult.getDriveId(); //Here you go :)
}
}
I want to implement Google Drive upload/download txt file to my Android app using Google Play Services, but I don't find a right way to do it.
In dropbox is very easy:
File file = new File("working-draft.txt");
FileInputStream inputStream = new FileInputStream(file);
Entry response = mDBApi.putFile("/magnum-opus.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
But for Google Drive with Google Play Services I have not found a simple way like that. Do you know how to?
By the way, I would like to use my own credentials (google service account) instead an user account, what is the way to implement it with Google Play Services?
Thanks in advance
Take a look here, it does everything you've mentioned. I don't know about the 'simple' requirement, though. Or go through the official DEMO code here. But it is definitely not a 'two-liner' endeavor.
I can't seem to find out how to move file into another folder using Drive.DriveApi from Google Play Services.
Only thing I see is using driveFolder.createFile(GoogleApiClient, MetadataChangeSet, Contents) but that's only if I'm going to upload a new file.
MetadataChangeSet.Builder() doesn't have any methods that point to file parent.
Is that impossible?
Changing parents is not currently exposed in the Google Play Services API. You can fall back to the web RESTful API to do this if you need to: parents collection. Just get the resourceId from the DriveId.