Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create & edit a spreadsheet file on google drive using Google Drive APIs only from my Android app?

My application contains a list of shifts. I'd like to save the list of the shifts into a spreadsheet file on to a google drive account. Since Google Spreadsheets API is using the deprecated Google Doc API in order to create spreadsheet files; how do I create and edit such file on a google drive, all from the java code inside my android application and without any user interaction (except authorizations), using Google Drive APIs only?

like image 980
D.Ginzbourg Avatar asked Jun 04 '13 20:06

D.Ginzbourg


2 Answers

Google Docs API is deprecated, but Sheets API (current: v3) is still living.

To fulfill the equivalent functionality of original Sheets+Docs combination, you should use Drive API to perform file manipulations such as search/move/creation/deletion.

In addition to the scopes for Drive API, add the following scope to your grant:

https://spreadsheets.google.com/feeds

If you're using GData client library and Google OAuth client library, it will be quite easy to setup both services after OAuth 2.0 authorization. Here is an example:

// Acquire clientId, clientSecret and refreshToken
...

// Create shared credential
GoogleCredential credential = new GoogleCredential.Builder()
            .setClientSecrets(clientId, clientSecret)
            .setJsonFactory(jsonFactory)
            .setTransport(transport)
            .build().setRefreshToken(refreshToken);

// Setup both servives
Drive driveService = new Drive.Builder(transport, jsonFactory, credential).build();
SpreadsheetService sheetService = new SpreadsheetService(...);
sheetService.setOAuth2Credentials(credential);  // only provided in newer releases
sheetService.useSsl();

Resource IDs in both APIs are identical, so you can search id of some file with Drive API methods and access worksheets in the file with Sheets API methods. Here is an example:

File file = driveService.files().get().setFields(...).execute();
String feedUrl = "https://spreadsheets.google.com/feeds/worksheets/" 
           + file.getId + "/private/full";
WorksheetFeed feed = sheetService.getFeed(feedUrl, WorksheetFeed.class);

If you get an error of "Token invalid - AuthSub token has wrong scope", appending query string of accessToken to the feedUrl may help.

feedUrl = feedUrl + "?access_token=" + credential.getAccessToken();

FYI, the list of Q&As I've referred when writing this answer.

  • "Is it possible to use the Google Drive API with Spreadsheet API"
  • "Get spreadsheet created with Drive SDK"
  • "Google Drive SDK alternateLink With OAuth2"
like image 180
chyiro Avatar answered Nov 05 '22 02:11

chyiro


You should take a look at Google Spreadsheet API 3.0. It supports JAVA which you can use in your Android application.

like image 4
JunYoung Gwak Avatar answered Nov 05 '22 02:11

JunYoung Gwak