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.
Related
I've been trying to simply call an api on an android build supporting 64 bit (IL2CPP build) and the UnityWebRequest class didnt seem to work. It's being called via a simple ui button click. It hits the webRequest.SendWebRequest(); and nothing happens. Ive tried the following samples. One, directly from the Unity docs for UnityWebRequest and others using standard HttpClient.
UnityWebRequest:
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
webRequest.SetRequestHeader("Authorization", "Bearer " + API_KEY);
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
debugText.text = ": Error: " + webRequest.error;
coroutineAllowed = false;
}
else
{
debugText.text = ":\nReceived: " + webRequest.downloadHandler.text;
dynamic jsonObj = JsonConvert.DeserializeObject(webRequest.downloadHandler.text);
foreach (var obj in jsonObj["businesses"])
{
businessResults.Add(new Business()
{
name = (string)obj["name"],
image_url = (string)obj["image_url"],
review_count = (string)obj["review_count"],
rating = (string)obj["rating"],
Coordinates = new Coordinates()
{
Latitude = (float)obj["coordinates"]["latitude"],
Longitude = (float)obj["coordinates"]["longitude"]
},
price = (string)obj["price"]
});
}
debugText.text = businessResults.Count.ToString();
//coroutineAllowed = true;
}
debugText.text = "getRequest 4";
}
}
This unfortunately did nothing at the yield return webRequest.SendWebRequest();
The next sample I tried was using HttpClient():
IEnumerator HttpClientCall(string uri) //possibly wrap in IEnumerator
{
debugText.text += "http coroutine started" +Environment.NewLine;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY);
var response = httpClient.GetAsync(uri);
if (response.Result.StatusCode != HttpStatusCode.OK)
{
debugText.text += "FAILED HTTP GET";
}
yield return response.Result.Content.ReadAsStringAsync();
dynamic jsonObj = JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result);
foreach (var obj in jsonObj["businesses"])
{
businessResults.Add(new Business()
{
name = (string)obj["name"],
image_url = (string)obj["image_url"],
review_count = (string)obj["review_count"],
rating = (string)obj["rating"],
Coordinates = new Coordinates()
{
Latitude = (float)obj["coordinates"]["latitude"],
Longitude = (float)obj["coordinates"]["longitude"]
},
price = (string)obj["price"]
});
debugText.text += Environment.NewLine + ((string)obj["name"]);
}
}
}
Once again, nothing when it hits yield return response.Result.Content.ReadAsStringAsync();
These all work on PC, and they both return results that i'm expecting.
The next thing i heard was about setting the android manifest application tag with android:usesCleartextTraffic="true"
This unfortunately, also did nothing for me lol. I know it has to be the 64 support, because this works on a standard build. The moment i go to build with 64 support, it doesnt work.
Any help on why it's not returning appropriately would be very helpful.
side note, i know the code is pretty ugly, but after i can figure out why the build doesnt work on the device a heavy refactoring is going to be in play. Thanks in advance!
So after a lot of trouble shooting ive found out why this was not working. The main issue seems to be stemming from my use of the standard Newtonsoft Json package when Unity, apparently, has their own internal JsonUtility class. After changing this:
dynamic jsonObj = JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result);
To This:
var js = JsonUtility.FromJson<T>(response.Result.Content.ReadAsStringAsync().Result);
my results are finally showing in the the apk build correctly.
Also, to note that to map correctly, the JsonUtility.FromJson must be typed to a class that exactly mirrors the incoming json object explicitly.
The page article that finally helped me with this issue is here.
P.S.
Thank you to #RetiredNinja for trying to help instead of just downvoting and saying nothing of value. You're amazing!
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.
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;
I am making a phonegap app for android. I am receiving a json string and trying to parse it . It's a very small data.
{"result":{ "node":"32"}
}
if iam using alert(request.responseText)
the result is displayed but if i return this request.responseText to the calling function and collect it there in a variable like var x= somefunction(); x contains undefined.
var jsonObj = sendPostRequest(url,nurl);
console.log(jsonObj+""); // GIVES UNDEFINED HERE AT THIS LINE BUT SAME STATEMENT WORKS IN sendPostRequest()
if(jsonObj){
var Json = JSON.parse(jsonObj);
console.log(json);
document.getElementById("gnodei").innerHTML= json.result.wEventId;
}
I can collect this response in a variable y inside somefunction() but on returning this data to the calling function nothing reaches there. I use the above json data x just below it but it doesn't work.
please suggest.
edit: `function sendPostRequest(url,nurl){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0){
console.log(request.status);
//alert(request.responseText);
var txt= request.responseText;
console.log(txt);
return txt;
}
}
}
request.open("POST",url, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(nurl);
}`
The ajax call. Also there are multiple functions calling this ajax call after preparing their url and nurl values so i need this function as it is. I only need to know how to get back the response in my calling function.
Thanks
Solved it: Created a function to be passed as callback to the sendPostRequest(url,nurl) method. This callback is called only after the ajax call finishes as correct status. The callback function assigns the data that can be used thereafter.
you can use:
var jsonData = $.parseJSON(stringJson);
I am trying to communicate with Facebook doing simple things. At the moment I can log a user in and post to their wall as them. But for whatever reason, I can't seem to access public information such as their name. I consistently get this error:
{"error":{"message":"Syntax error \"Expected end of string instead of \"?\".\" at character 4: name?access_token=MYACCESSTOKEN","type":"OAuthException","code":2500}}
Here is the call:
SampleRequestListener srl = new SampleRequestListener();
AsyncFacebookRunner afr = new AsyncFacebookRunner(facebook);
afr.request("http://graph.facebook.com/me?fields=name", (RequestListener)srl);
That call is made within a validated session (in the onComplete portion of the DialogListener for .Authorize). Using my access_token and the exact same string as above I can get the request to work just fine at http://developers.facebook.com/tools/explorer/
The error occurs whilst parsing the response in the RequestListener.onComplete
JSONObject json = Util.parseJson(response);
final String name = json.getString("name");
System.out.println("Hi, my name is " + name);
Thank you for your time. All input is welcomed.
UPDATE *
There are two things going on. In the facebook API, Util.openUrl was appending a "?" between the field name and the access_token (as the answer below pointed out). This seems odd. I wonder if I pulled an old version of the API or something. You would think that would be set up correctly.
Also, I called the method incorrectly:
This:
afr.request("http://graph.facebook.com/me?fields=name", (RequestListener)srl);
Should be:
afr.request("me?fields=name", (RequestListener)srl);
If you are using com.facebook.Request class then just use the following form of constructor: Request(Session session, String graphPath, Bundle parameters, HttpMethod httpMethod, Callback callback) and pass your parameters in "parameters" parameter.
Just like:
if (GlobalApplication.accessToken != null && !GlobalApplication.accessToken.isExpired()) {
/* make the API call */
Bundle b = new Bundle();
b.putString("fields", "id,created_time,description,embed_html,name,source,picture");
new GraphRequest(GlobalApplication.accessToken, "/me/videos",
b, HttpMethod.GET, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.i("", "");
String string = response.toString();
JSONObject object = response.getJSONObject();
JSONArray array = response.getJSONArray();
Log.i("", "");
}
}).executeAsync();
Looks like the actual request being sent is something like
/me?fields=name?access_token=MYACCESSTOKEN
and that of course is wrong; it should be an ampersand before the second parameter and not a question mark.
You’d have to look for the location in the code where the access token is added as parameter. At that point there should be a check for whether this URL already contains a question mark or not before appending the access_token parameter.