How to insert row after the last row with value? - android

I am inserting data into a spreadsheet with the new Google Sheets API v4, the code works perfect and the data it is inserted well in the sheet.
But how to find out the last row with data to add the data after this ?
List<List<Object>> arrData = getData();
ValueRange oRange = new ValueRange();
oRange.setRange("Pedidos!AXXXXXXX"); // I NEED THE NUMBER OF THE LAST ROW
oRange.setValues(arrData);
List<ValueRange> oList = new ArrayList<>();
oList.add(oRange);
BatchUpdateValuesRequest oRequest = new BatchUpdateValuesRequest();
oRequest.setValueInputOption("RAW");
oRequest.setData(oList);
BatchUpdateValuesResponse oResp1 = mService.spreadsheets().values().batchUpdate("ID_SPREADSHEET", oRequest).execute();
Is there some trick in the A1 notation for this?
I need an equivalent to .getLastRow from Google Apps Script.

If you use the append feature and set the range to the entire sheet, the API will find the last row and append the new data after it.
This web page explains it.
https://developers.google.com/sheets/api/guides/values#appending_values
Here is some sample code:
String range="Sheet1";
insertData.setValues(rows);
AppendValuesResponse response=service.spreadsheets().values()
.append(spreadsheetId,range,insertData).setValueInputOption("USER_ENTERED")
.execute();
Note that the response will tell you where it was inserted.

The v4 API has no way to ask "what is the last row with data", as it's a different style of API than the Apps Script API. You can infer the last row yourself by requesting the data and counting the offset from your first requested row to the last returned row.

You can use AppendCellsRequest to append a row. The below methods should get you going. I haven't included the getRowDataListForCellStrings method as it is rather application specific.
First create a Request object containing a AppendCellsRequest:
public BatchUpdateSpreadsheetResponse appendWorksheet(String cellValues) throws SpreadsheetException {
AppendCellsRequest appendRequest = new AppendCellsRequest();
appendRequest.setSheetId( mSheet.getProperties().getSheetId() );
appendRequest.setRows( getRowDataListForCellStrings(cellValues) );
appendRequest.setFields("userEnteredValue");
Request req = new Request();
req.setAppendCells( appendRequest );
return executeBatchRequest(req);
}
Then call batchUpdate on the spreadsheets() interface:
BatchUpdateSpreadsheetResponse executeBatchRequest(Request request) throws SpreadsheetException {
List<Request> requests = new ArrayList<>();
requests.add( request );
BatchUpdateSpreadsheetRequest batchRequest = new BatchUpdateSpreadsheetRequest();
batchRequest.setRequests( requests );
try {
return mService.spreadsheets().batchUpdate(mSpreadsheet.getSpreadsheetId(), batchRequest).execute();
} catch (IOException e) {
throw new SpreadsheetException(e);
}
}
Unfortunately there doesn't seem to be a way to know which rows were updated. Not does is seem possible to set valueInputOption when appending in this way.

There is actually a way to ask the API.
I am using this on my node.js client (pretty sure it's very similar)
var sheets = google.sheets('v4');
sheets.spreadsheets.get({
auth: auth,
spreadsheetId: 'spreadsheet_id',
includeGridData: true
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
} else {
var last_row = response.sheets[0].data[0].rowData.length;
}
});

Related

Mongodb- How to get data from a partition that was created by other user?

I am using Realm MongoDB for my android app, and I have a problem:
I have different users in my app, and each user has his "cards". The partition of each user's cards is:
"Card=userID".
So, I want to be able to send a card from one user to the other. I do it via a link that includes userID and specific cardID.
So my code looks something like:
Realm.init(this);
mainApp = new App(new AppConfiguration.Builder(APP_ID).defaultSyncErrorHandler((session, error) ->
Log.e("TAG()", "Sync error: ${error.errorMessage}")
).build());
//TEMP CODE
String partition = "Card=611d7n582w36796ce34af106"; //test partition of another user
if(mainApp.currentUser() != null) {
SyncConfiguration config = new SyncConfiguration.Builder(
mainApp.currentUser(),
partition)
.build();
Realm realmLinkCard = Realm.getInstance(config);
Log.d(TAG, "onCreate: cards found- " + realmLinkCard.where(Card.class).findAll().size());
}
The last log always shows 0. I know there are cards for sure because if the user that created the corresponding partition is signed in then it does find the cards.
permissions are set to true for both read and write for the whole sync.
What can the problem be?
You cannot access a Realm by a user who has a different partition.
Instead you can create a mongodb function and call it from your user.
Make your function here:
Check here on How to create a function
And call it by checking here on How to call a function from client
Quick example of a realm function:
exports = async function funcName(partition) {
const cluster = context.services.get('myclustername');
const mycollection = cluster.db('mydbname').collection('mycollectionname');
let result = [];
try {
result = mycollection.findOne({
_partition: partition,
});
} catch (e) {
result.push(e);
return result;
}
return result;
};
To call it, please see above for the documentation as I'm not an Android developper.

Google Drive REST API : file.getCreatedTime() returns always null

I am working with Android Quickstart for Google Drive Rest APi provided at the below link. Android Quickstart
The sample code works fine as is. However when I try to get other details from files like getCreatedTime() or GetWevViewLink() 'null' is returned. Only getName() and getId() returns values.
Google Drive REST APIs v3 would only return only certain default fields. If you need some field, you have to explicitly request it by setting it with .setFields() method.
Modify your code like this -
private List<String> getDataFromApi() throws IOException {
// Get a list of up to 10 files.
List<String> fileInfo = new ArrayList<String>();
FileList result = mService.files().list()
.setPageSize(10)
// see createdTime added to list of requested fields
.setFields("nextPageToken, files(createdTime,id,name)")
.execute();
List<File> files = result.getFiles();
if (files != null) {
for (File file : files) {
fileInfo.add(String.format("%s (%s)\n",
file.getName(), file.getId()));
}
}
return fileInfo;
}
You can read more about this behavior here https://developers.google.com/drive/v3/web/migration
Updated link https://developers.google.com/drive/api/v2/migration
Quoting from the above link -
Notable changes
Full resources are no longer returned by default. Use the fields query parameter to request specific fields to be returned. If left unspecified only a subset of commonly used fields are returned.
Accept the answer if it works for you so that others facing this issue might also get benefited.
I think you need to use the Metadata class to be able to use the getCreatedDate as indicated in Working with File and Folder Metadata.
Then try something like:
ResultCallback<MetadataResult> metadataRetrievedCallback = new
ResultCallback<MetadataResult>() {
#Override
public void onResult(MetadataResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while trying to fetch metadata");
return;
}
//show the date when file was created
Metadata metadata = result.getMetadata();
showMessage("File was created on " + metadata.getCreatedDate() );
}
}

How do I add "sheetId": XXXXXX to my Google Sheets v4 function batchupdate?

I'm almost finished with my application where I'm able to do a simple delete off of Google Spraedsheet data. However, I have not been able to find a method where I could add the sheetId and its respective GID # to the request arraylist.
private void deleteRow()
{
List<Request> requests = new ArrayList<>();
DeleteDimensionRequest deleteDimensionRequest = new DeleteDimensionRequest();
DimensionRange dimensionRange = new DimensionRange();
dimensionRange.getDimension();
dimensionRange.setStartIndex(13);
dimensionRange.setEndIndex(14);
deleteDimensionRequest.setRange(dimensionRange);
Sheets.Spreadsheets spreadsheets = null;
requests.add(new Request()
//There should be a function call or some sort for me to
//add a sheetid... if I do the updatesheets property here
//I get an error message saying that there's already a kind
//and I cannot set the id
.setDeleteDimension(deleteDimensionRequest)
);
BatchUpdateSpreadsheetRequest batchUpdateRequest = new BatchUpdateSpreadsheetRequest()
.setRequests(requests);
try
{
mService.spreadsheets().batchUpdate("SPREADSHEETID GOES HERE", batchUpdateRequest).execute();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Does anyone know the strategy to add the sheet values into the request arraylist?
The function calls were actually available after creating a new constructor for DimensionRange.
Simply do:
dimensionRange.setDimension("ROWS");
dimensionRange.setSheetId(XXXXX);
to finish the JSON post request to Sheets API...

How to get Playlist ID on search: list (playlist type)

i'm stuck on my app development: i'm trying to get the Playlist ID on a youtube search list (i'm searching for playlists). I am looking at the youtube api site and on the test site it comes with playlist id. On my app, i do the same, but i don't get the ID, or i'm not seeing it on my "item" on the iterated code.
I know that currently is searching for video ID and it is not correct. I've tried so far:
item.id
item.getId().getPlaylistId()
item.getId().playlistId
also entirely iniside item.
I let you my async task code:
SearchListResponse searchResponse;
try {
YouTube.Search.List search = mYouTubeDataApi.search().list("id,snippet");
search.setKey(ApiKey.YOUTUBE_API_KEY);
search.setQ(mTitle);
search.setType("playlist");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(YOUTUBE_PLAYLIST_MAX_RESULTS);
searchResponse = search.execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (searchResponse == null) {
Log.e(TAG, "Failed to get playlist");
return null;
}
ArrayList videoIds = new ArrayList();
for (SearchResult item : searchResponse.getItems()) {
//this is what i was talking about. My search result item
//is not showing me any playlist id
videoIds.add(item.getId().getVideoId());
}
You are correct. The best way to get the list of playlists is to use search.list request.
You will have to specify type=playlist and the title of the video for the q parameter.
Search:list will gives you the result that match the query parameters specified in your request. You can also configure queries to only retrieve a specific type of resource.
Note that this may not give you the playlists you're expecting if the title of the video isn't specific enough.
https://www.googleapis.com/youtube/v3/search?part=snippet&q=VIDEO_TITLE_HERE&type=playlist&key=API_KEY_HERE
i've already figured it out by paying attention to my own code.
The data received is setted by the fields:
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
i was missing the id/playlistId on my search, so i added it:
search.setFields("items(id/kind,id/videoId,id/playlistId,snippet/title,snippet/thumbnails/default/url)");
Now i'm getting my playlist id (and a lot of other info i did not need).

Can't get all BookMarkedRooms when using PrivateDataManager with (a)Smack. Always returns only the last bookmark

I added 3-4 Persistent Conference rooms and try to get connect ever conference room at app start time but when i tried to get all bookmarked rooms it will just returns me one room.
and that room is last time added.
muc = new MultiMUC(connection, "g2#conference.msngr.com");
try {
muc.create("g2");
Form form = muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
FormField ff = new FormField("muc#roomconfig_persistentroom");
ff.setType(FormField.TYPE_BOOLEAN);
ff.addValue("0");
ff.setRequired(true);
ff.setLabel("Make Room Persistent?");
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
List owners = new ArrayList();
owners.add("userdev#msngr.com");
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
muc.sendConfigurationForm(submitForm);
Bookmarks bookmarks = new Bookmarks();
BookmarkedConferenceImpl conference = new BookmarkedConferenceImpl("g2#conference.msngr.com");
conference.setName("My Favorite Room");
conference.setAutoJoin(true);
bookmarks.addBookmarkedConference(conference);
try
{
PrivateDataManager manager = new PrivateDataManager(connection,"userdev#msngr.com");
manager.setPrivateData(bookmarks);
}
catch (Exception e) { }
but when i am try to get all BookMarkedRoom it return one last added Coference room.
BookmarkManager bm = BookmarkManager.getBookmarkManager(connection);
Collection<BookmarkedConference> rooms=bm.getBookmarkedConferences() ;
for(BookmarkedConference room:rooms){
MultiUserChat muc = new MultiMUC(connection, room.getJid());
muc.join(uid);
muc.addMessageListener(listener);
}
It seems that you are always overwriting the Bookmarks PrivateData with the latest MUC that got created.
Instead of using the PrivateDataManager directly, use the specialized BookmarkManager for this job. BookmarkManager comes with three methods that should do the job for you conviniently
addBookmarkedConference()
getBookmarkedConferences()
removeBookmarkedConference()

Categories

Resources