How to update/write data to google spreadsheet api android (api v4) - android

I have been working on an application where I need to write and update data to a spreadsheet using google spreadsheet api. I have followed the Android Quickstart provided by google Google Sheets API
Android Quickstart and was able to retreive data from the google spreadsheet but I am not able to understand how to write data. Please help

If you followed the Quickstart tutorial correctly, then it you are few steps from learning how to write data.
In the code provided in the Quickstart tutorial, change the line
private static final String[] SCOPES = { SheetsScopes.SPREADSHEETS_READONLY };
to:
private static final String[] SCOPES = { SheetsScopes.SPREADSHEETS };
This will grant access to write on a spreadsheet.
And instead of something like
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
you must create your own ValueRange instance, valueRange in this example, and then write:
this.mService.spreadsheets().values().update(spreadsheetId, range, valueRange)
.setValueInputOption("RAW")
.execute();
Choose the ValueInputOption of your preference.

After a lot of searching for a concrete example and not finding it, only here I was able to get something that worked for me, with the addition that I put for beginners like me. Thanks to #Veiga
Object a1 = new Object();
a1 = "TEST Row 1 Column A";
Object b1 = new Object();
b1 = "TEST Row 1 Column B";
Object a2 = new Object();
a2 = "TEST Row 2 Column A";
Object b2 = new Object();
b2 = "TEST Row 2 Column B";
ValueRange valueRange = new ValueRange();
valueRange.setValues(
Arrays.asList(
Arrays.asList(a1, b1),
Arrays.asList(a2, b2)));
this.mService.spreadsheets().values().update(spreadsheetId, "A1:B2", valueRange)
.setValueInputOption("RAW")
.execute();
I leave this concrete example, because other threads that I saw, throw compilation problems such as "List<String> is not acceptable as List<Object>".
But I thank those collaborators, example #k9yosh in the answer to How to assign a value to a ValueRange variable in java?
, because they were also an inspiration for me to develop a concrete solution to this case.

Please try going through Manage List-based and Cell-based Feeds to read and modify worksheets and data in Google Sheets.
However, since you're looking for the latest, as indicated in your post's title, and since version 4 of the Google Sheets API is now available, the following references will be very helpful too:
Google Sheets API v4
Migrate to the Google Sheets API

Related

Using the google sheets api after completing quickstart tutorial

I'm pretty new to Android app development so please forgive my naivety.
I'm currently trying to develop an app that can pull data from a google spreadsheet and write data to it.
I've completed the quickstart tutorial so my code is the same as that right now. It all works correctly.
My issue is I need to be able to read from my own spreadsheet and I don't really understand the code used so I'm struggling to know where to start.
I've looked at this to try and implement the authorisation in fewer steps which I thought might make the code easier to understand - but again my lack of knowledge means I don't know how this fits into all the methods I currently have.
I've looked at the developer documentation and tried to replace the code from the quickstart which retrieves data from the app with this:
ValueRange result = service.spreadsheets().values().get(spreadsheetId, range).execute();
int numRows = result.getValues() != null ? result.getValues().size() : 0;
System.out.printf("%d rows retrieved.", numRows);
But again this is different to the code I already have so doesn't fit in as the getDataFromApi() method requires a return statement. I've tried just changing the spreadsheetId to that of my own spreadsheet and changing the range value to the cells I need,
/**
* Fetch a list of names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
* #return List of names and majors
* #throws IOException
*/
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1-hL78Jm9-HijPx9UHthFxcXatkIhA2FR-AQ1lrCUbEg";
String range = "Go Mix 12 0506!B6:D";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(1) + ", " + row.get(3));
}
}
return results;
}
but I'm clearly going about it wrong because I get this error:
Invalid index 3, size is 3
I've also followed up to video 15 on this tutorial but it bypasses the need for any authorisation so didn't help.
Basically I've hit a brick wall and need someone to explain to me in simple terms how I can either work with the code from the quickstart tutorial to work with my own spreadsheet and fix that error! OR (more preferable to myself) explain how to do it myself from scratch. NB the spreadsheet cannot be public so I will need authorisation.
I hope that all makes sense!
You are asking to retrieve three columns of data (B through D), but then attempting to read a fourth column (rows.get(3)). In Java (and in most programming languages), lists and arrays are 0-based. So if you want the first item, you call list.get(0), and if you want the third you call list.get(2). This is evident based on the fact that the error message tells you your index of 3 is invalid since the list is size 3 -- you're attempting to read something beyond the end of the list.

Can't set KeyConditionExpression parameter in DynamoDb for Android

I'm using the Amazon AWS DynamoDB for android, however, there's no way for me to set the KeyConditionExpression for a query.
See [http://docs.aws.amazon.com/AWSAndroidSDK/latest/javadoc/com/amazonaws/mobileconnectors/dynamodbv2/dynamodbmapper/DynamoDBQueryExpression.html][1]. The DynamoDBQueryExpression class is missing a withKeyConditionExpression() method.
I'm trying to make a query against dynamodb table but there's no way for me to set the key condition values.
Unfortunately keyConditionExpression No Longer exist for Java / Android. I wasted a significant amount of time because it still exist for Objective-C / iOS.
And since all AWS docs still refer to it, I thought I was in error. Once I have the new code written and working, I will document the replacement here.
The keyConditionExpression is set as follows:
AWSDynamoDBQueryExpression *queryExpression = [AWSDynamoDBQueryExpression new];
queryExpression.keyConditionExpression = #"#bookId = :bookId";
queryExpression.expressionAttributeNames = #{
#"#bookId" : #"bookId",
};
queryExpression.expressionAttributeValues = #{
#":bookId" : self.selectedBookId,
};
I encountered the similar problem for my Android Application where .withKeyConditionExpression() method was giving an error. Instead of that, I used:
TestTable object = new TestTable();
object.setHashKeyValue("12345"); //Set the value for HashKey
String queryString = "soverflow";
Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.BEGINS_WITH.toString())
.withAttributeValueList(new AttributeValue().withS(queryString.toString()));
DynamoDBQueryExpression newQueryExpression = new DynamoDBQueryExpression()
.withHashKeyValues(object)
.withRangeKeyCondition("AttributeName", rangeKeyCondition)
.withConsistentRead(false);
PaginatedQueryList<TestTable> result = mapper.query(TestTable.class, newQueryExpression);
The Point is that If you are Querying a table, the HashKey and the RangeKey will be the Partition Keys of the table and If you are Querying an Index, the Hash Key and the Range Key will be the partition keys of the Index.
Make sure to use the Annotations properly in the Table Class and to add Index's ARN to the Policy for authorization.

How to write and update data to google spreadsheet android (api v4)

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();
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

Possible to query against the count of an included key?

I have an application where I need to return the first user found that meets certain criteria, some of that criteria is having a certain number of objects stored.
For example, let's say I want to return the first store I can find that has at-least 3 employees with atleast two children. I know, what an odd-ball example. So I would have a query something like this:
PFUser.query()?
.whereKey("objectId", notEqualTo: PFUser.currentUser()?.objectId!)
.includeKey("stores.employees.children")
// .whereCountForkey("stores.employees", greaterThan: 2)
// .whereCountForKey("stores.employees.children", greaterThan: 1)
.getFirstObject();
Notice the commented out lines, I'm trying to find a way to do soemthing like this in a single query. I'm using parse, which I believe uses MongoDB on the back end, but I don't believe you can execute custom database queries..?
This is a mobile application for both iOS and Android, although the code shown is in SWIFT I have two variations of the project. Examples in either swift, obj-C, Java, or C# will be fine.
Also more than happy with Cloud-code solutions.
There is an example in the documentation
var Team = Parse.Object.extend("Team");
var teamQuery = new Parse.Query(Team);
teamQuery.greaterThan("winPct", 0.5);
var userQuery = new Parse.Query(Parse.User);
userQuery.matchesKeyInQuery("hometown", "city", teamQuery);
userQuery.find({
success: function(results) {
// results has the list of users with a hometown team with a winning record
}
});

Working with Entities - Google App Engine

I´m coding an app that will allow the user to take a picture, add some title and description to it and upload it to Google´s Servers. That package (picture+title+description) is named "Gift". I've used Google´s automated Backend Engine generator and added an #Entity class named Gift.
After taking the picture and clicking on submit, the "Gift" is successfully sent to Google and looking my Google App Engine Dashboard, now I have a Gift with a proper ID, a Blob (image), Description and Title.
Now what I want to do is show all those "Gifts"/Entities on a ListView, so that the user can interact with the "Gifts". What is the best way to do that?
I think I found the answer, here´s the code I´m using:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter keyFilter = new FilterPredicate(Entity.KEY_RESERVED_PROPERTY,
FilterOperator.GREATER_THAN,
0);
Query q = new Query("Gift").setFilter(keyFilter);
PreparedQuery pq = datastore.prepare(q);
for (Entity result : pq.asIterable()){
String title = (String) result.getProperty("title");
String description = (String) result.getProperty("description");
Blob bmp = (Blob) result.getProperty("bmp");
//new Object using variables above
}
This way I think I can iterate through the results and associate them with new objects of the type Gift.

Categories

Resources