Unable to update a getstream activity created from json - android

If we update an activity after retrieving from stream, we are able to update
String feedId = "ef202000-3f6b-11e7-8080-800171e94936";
Feed feed = StreamUtils.getStreamClient().newFeed(Constants.FEED_SLUG, "feed_66_103");
NotificationActivityServiceImpl<MessageItem> userMessagesActivityService = feed.newNotificationActivityService(MessageItem.class);
FeedFilter filter = new FeedFilter.Builder().withIdGreaterThanEquals(feedId).withLimit(1).build();
StreamResponse<NotificationActivity<MessageItem>> userMessageItems = userMessagesActivityService.getActivities(filter, false, false);
if (userMessageItems != null && userMessageItems.getResults().size() != 0) {
for (NotificationActivity<MessageItem> messageItemNotificationActivity : userMessageItems.getResults()) {
for (MessageItem messageItem : messageItemNotificationActivity.getActivities()) {
messageItem.setMessage_status(MESSAGE_STATUS_READ);
userMessagesActivityService.updateActivities(Collections.singletonList(messageItem));
Log.d("Message json", new Gson().toJson(messageItem));
}
}
}
But, If we update it by constructing the activity, we are unable to update
Feed feed = StreamUtils.getStreamClient().newFeed(Constants.FEED_SLUG, "chat_66_103");
String messageJson = "{\"channel_id\":\"feed_66_103\",\"message\":{\"message_text\":\"Test message\"},\"message_status\":\"DELIVERED\",\"receivers\":[103],\"actor\":\"66\",\"foreignId\":\"66_103_1495511846405\",\"id\":\"ef202000-3f6b-11e7-8080-800171e94936\",\"object\":\"delivery_message\",\"time\":\"May 23, 2017 9:27:26 AM\",\"to\":[],\"verb\":\"delivery_message\"}";
MessageItem messageItem = new Gson().fromJson(messageJson, MessageItem.class);
messageItem.setMessage_status(MESSAGE_STATUS_READ);
NotificationActivityServiceImpl<MessageItem> userMessagesActivityService = feed.newNotificationActivityService(MessageItem.class);
userMessagesActivityService.updateActivities(Collections.singletonList(messageItem));
Log.d("Message json", new Gson().toJson(messageItem));
In the setMessage_status method, I'm changing values of variables object, verb, message_status
Here even the logs printing the same object. We don't know what we are missing.
We tried it from python client as well. Same issue there as well.

Updating activities is done using your foreign ID. Currently your payload is sending this value in a field called foreignId and our endpoint will be expecting foreign_id.

Related

Creating Notes in LinkedNotebook

I am trying to create note in a shared notebook which is already shared with me. The notebook is shared with me with priveleges to modify its contents (SharedNotebookPrivilegeLevel.MODIFY_NOTEBOOK_PLUS_ACTIVITY), and I can create notes in that notebook using Evernote web client. But when I trying to create a note using SDK I received an EDAMUserException(errorCode:PERMISSION_DENIED, parameter:authenticationToken). Below is my code
Note note = new Note();
note.setContent(EvernoteUtil.NOTE_PREFIX + content + EvernoteUtil.NOTE_SUFFIX);
note.setTitle(title);
EvernoteSession evernoteSession = EvernoteSession.getInstance();
List<LinkedNotebook> linkedNotebooks = evernoteSession
.getEvernoteClientFactory()
.getNoteStoreClient()
.listLinkedNotebooks();
LinkedNotebook current = null;
for (LinkedNotebook linkedNotebook : linkedNotebooks) {
if (linkedNotebook.getShareName().equals(notebookName)) {
current = linkedNotebook;
}
}
if (current == null)
throw new IllegalStateException();
THttpClient tHttpClient = new THttpClient(current.getNoteStoreUrl());
TBinaryProtocol tBinaryProtocol = new TBinaryProtocol(tHttpClient);
NoteStore.Client client = new NoteStore.Client(tBinaryProtocol, tBinaryProtocol);
AuthenticationResult authenticationResult = client.authenticateToSharedNotebook(current.getShareKey(),
evernoteSession.getAuthToken());
String shareToken = authenticationResult.getAuthenticationToken();
SharedNotebook sharedNotebook = client.getSharedNotebookByAuth(shareToken);
String sharedNotebookGuid = sharedNotebook.getNotebookGuid();
note.setGuid(sharedNotebookGuid);
Note createdNote = client.createNote(shareToken, note);
return createdNote;
I've used this article to create notes.
One mistake I found is that
note.setGuid(sharedNotebookGuid);
has to be
note.setNotebookGuid(sharedNotebookGuid);

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 insert row after the last row with value?

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

Calling this function in Android using Rhino

I am working on a project where I need to download a javascript and use it to calculate some values. This is already working on iOS so the javascript seems to be just fine.
Here is the stripped down javascript (I have removed the content as I do not own the script):
var resultArray = [];
function calculateRemainingAmountForForecastWeeks(numberOfWeeks, weeklyDisposable, easing, safetyZone, safetyZoneEasing, overSpentThisWeek) {
// Some calculations...
resultArray[numberOfWeeks] = spentBeyondForecast;
}
I am using Rhino and here is what I do:
org.mozilla.javascript.Context rhino = org.mozilla.javascript.Context.enter();
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
rhino.evaluateString(scope, WeeklyApplication.getCalculatorJS(), "JavaScript", 0, null);
Object obj = scope.get("calculateRemainingAmountForForecastWeeks", scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object[] params = new Object[]{numberOfWeeks, weeklyDisposable, easing, safetyZone, safetyZoneEasing, overSpentThisWeek};
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = org.mozilla.javascript.Context.toString(jsResult);
Log.d(TAG, "SKN-calculate3=" + result);
}
} finally {
org.mozilla.javascript.Context.exit();
}
I know it is not the most optimized use of scope here, but I just need to get it working first. I keep getting "undefined" in the result String, what am I doing wrong here?
And when I do get this working, how do I then get the values stored in the "resultArray"?
Thank you
Søren
From code that you posted, it looks like function calculateRemainingAmountForForecastWeeks() doesn't return anything, so it's ok to get Undefined from it.
Getting value from resultArray is easy, as it's just a field in your scope scriptable object:
Object[] params = new Object[]{numberOfWeeks, weeklyDisposable, easing, safetyZone, safetyZoneEasing, overSpentThisWeek};
// function doesn't return anything
jsFunction.call(rhino, scope, scope, params);
NativeArray resultArray = (NativeArray) scope.get("resultArray", scope);
double result = ((Number) resultArray.get(numberOfWeeks)).getDoubleValue();
Log.d(TAG, "SKN-calculate3=" + result);
Note: of course, I don't know what your types are, so probably you'd have to update this snippet to make it work for you.

Intel App-Framework -displaying JSON data

How to display JSON coming from php in intel App Framwork app. I have tried .getJSON() and .getJSONP() methods. Is there any full guide explaining these methods and how to use them?
Here are documentations for $.getJSON() and $.jsonP()
found the answer .
function getRaceData() {
var postBody = "";
postBody = "rid="+theRID;
var parameters = new AppMobi.Device.RemoteDataParameters();
parameters.url = "http://MyWebSite.com/php_src/getRaceData.php";
parameters.id = "1007";
parameters.method = "POST";
parameters.body = postBody;
jq.ui.showMask('loading race data');
AppMobi.device.getRemoteDataExt(parameters);
}
//then somewhere in your event handler, check the ID of the response and process the JSON....
case 1007: //got race data
var raceData = jq.parseJSON(event.response);
jq("#raceRCList").hide();
jq("#raceRCname").html(raceData.race_name);
jq("#raceRCdate").val(raceData.date);
jq("#raceRCstart").val(raceData.start_time);
jq("#raceRCData").show();
break;

Categories

Resources