3
votes

I have followed the Android Quickstart provided by google Google Sheets API Android Quickstart and was able to retrieve data from the google spreadsheet but I am not able to understand how to write and update single or multiple data.

I read this code from StackOverflow, I think It's good but I can't understand how to set (valueRange) object here

this.mService.spreadsheets().values().update(spreadsheetId, range, valueRange)
                .setValueInputOption("RAW")
                .execute();
1
me too having same problem... some help please.... - Ramkumar P

1 Answers

4
votes

In case you still need the answer, or for anyone else who does:

I faced the same issue too, and from the docs, I was able to work this out. Here's a method in which i write the data to the sheet

private void writeDataToApi() throws IOException {
            String spreadsheetId = "the_spreadsheet_id_like_the_google_example";
            String range = "YourSheetName!A1:B1"; //Read the docs on how these ranges work.
            //Currently, this is the range of a single row which would return
            //as [[objA, objB]] if major dimension is set as ROW.(default).
            // would be [[objA],[objB]] if its set to COLUMN. Read the doc for more info.

            //for the values that you want to input, create a list of object lists
            List<List<Object>> values = new ArrayList<>();

            //Where each value represents the list of objects that is to be written to a range
            //I simply want to edit a single row, so I use a single list of objects
            List<Object> data1 = new ArrayList<>();
            data1.add("objA");
            data1.add("objB");

            //There are obviously more dynamic ways to do these, but you get the picture
            values.add(data1);

            //Create the valuerange object and set its fields
            ValueRange valueRange = new ValueRange();
            valueRange.setMajorDimension("ROWS");
            valueRange.setRange(range);
            valueRange.setValues(values);

            //then gloriously execute this copy-pasted code ;)
            this.mService.spreadsheets().values()
                    .update(spreadsheetId, range, valueRange)
                    .setValueInputOption("RAW")
                    .execute();

            //Try calling this method before executing the readDataFromApi method, 
            //and you'll see the immediate change

        }

I hope this helped. And for more info, pls see the docs

EDIT: Also remember to change scope from SheetsScopes.SPREADSHEETS_READONLY to SheetsScopes.SPREADSHEETS