Intel App-Framework -displaying JSON data - android

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;

Related

UnityWebRequest does nothing on IL2CPP Build

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!

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'?

I'm trying to upload images to firebase through firebase storage, and then create a document in firestore containing urls of the said uploaded images. For this,i use this function
void uploadImageAndCreatePage(List<File> imageFile) async {
var storage = FirebaseStorage.instance;
for(int j = 0; j<imageFile.length; j++) {
StorageReference ref = storage.ref().child("photo"+Random().nextInt(3413555).toString()+j.toString());
StorageUploadTask uploadTask = ref.putFile(imageFile[j]);
var url = "";
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
url = dowurl.toString();
downUrl.add(url);
print("url is:" +downUrl.toString());
}
for(int i = 0; i<imageFile.length;i++){
if(i == 0){
map['ImgUrl'] = downUrl[0];
}
map['Img$i'] = downUrl[i+1 < downUrl.length?i+1:i];
}
var doc = await _reference.collection('Products').document("${titleController.text}").get();
doc.reference.setData(map);
doc.reference.collection('Reviews').document("DummyRev").setData({
"name":"null",
});
print("done");
}
The code works fine until it gets to the part where i set the data using documentreference.setData, which takes in a map value. I have this map defined as Map<String,String> map = new Map() , but it still says it's not a subtype of _InternalLinkedHashMap.. where am i going wrong with this? i have also tried to use a Map<dynamic,dynamic> and Map<String,dynamic, to no avail.
Try this
doc.reference.setData(Map<String, dynamic>.from(map));
As answered by Josteve, the issue seems to be because the map type just needs to be String,dynamic at runtime, anything else will throw a type error like that, probably has something to with the way the plugin handles the json request. Just cast it using
Map.from(yourMap)

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.

How to use HttpWebRequest with async & await

I am new to Xamarin and C# as well. I try to make a Http request to my server with some information.
In general with android Native a uses AsyncTask and HttpClient for that. and build a json object or name value pair, and encrypt it to integrate information with the request.
But when I try to do the same with xamarin I get some problems.
if I try to import the namespace
using System.Net.Http.HttpClient
than my xamarin not have this namespace
Because of the above problem I try to use HttpWebRequest. But when I go for use it with the asyc and await I am not getting any response from server.
I am new to xamarin so I am not sure about async and await keyword.
I read lot of articles but No luck :(
on Click of the Button I call the below Method
public async Task<int> ValidateUser(){
try{
var request = HttpWebRequest.Create (URL);
request.Method = "GET/POST";
String postString = String.Format ("AAA ={0}&BBB={1}&CCC={2}", "111",
"222","333");
byte[] postByte = Encoding.UTF8.GetBytes (postString);
Stream st = request.GetRequestStream ();
//I am reaching here
Console.WriteLine("Check for Validity");
request.ContentLength = postByte.Length;
st.Write (postByte, 0, postByte.Length);
st.Close ();
Task<Stream> contentTask = request.GetRequestStreamAsync();
Stream response = await contentTask;
String str = response.ToString();
// this is not getting printed in Console
Console.WriteLine("=====>>"+str);
}
catch (WebException exception) {
string responseText;
using (var reader = new StreamReader(exception.Response.GetResponseStream())) {
responseText = reader.ReadToEnd ();
Console.WriteLine ("====Dude Error"+responseText);
}
}catch(Exception e){
}
return 1;
}
Any help will be appreciated
Consider using RestSharp, a component created for Xamarin to facilitate web requests. Click here for more info on the component. It will facilitate allot of things about webrequesting ( like serialization, automatic return type detection,... )
Your code would look something like this with restsharp:
public async Task<int> ValidateUser(){
var client = RestClient (URL);
var request = new RestRequest ("AAA ={0}&BBB={1}&CCC={2}", "111",
"222","333");
client.ExecuteAsync (request, response => {
WebApiResponse webApiResponse = new WebApiResponse ();
webApiResponse.Content = response.Content;
webApiResponse.StatusCode = response.StatusCode;
webApiResponse.ResponseStatus = (WebApiResponseStatus)response.ResponseStatus;
return webApiResponse.Content;
});
return -1
}
Using HttpWebRequest is a bad idea, instead it would be better to focus on why you don't have the System.Net.Http.* namespace. Imho the most likely cause is that you didn't add System.Net.Http as a reference to your project.
Here's how you add System.Net.Http.* to your project.
In Visual Studio 2013:
Open the solution
Open the project
Open the Solution Explorer
Right-click on References
Add Reference
Click on 'Search Assemblies'
Type in 'Http'
Select System.Net.Http
Press 'OK'
In Xamarin Studio:
Open the solution
Open the project
Open the Solution Explorer
Right-click on References
Edit References
Type in 'Http'
Select System.Net.Http
Press 'OK'
Afterwards there should be no problems resolving System.Net.Http when 'using System.Net.Http;'

Zend framework 2 + Android Mobile + ZfcUser Authentication

I need to authenticate via Android on my website (Zend Framework2+ZfcUser+ZfcUserDoctrineORM).
I want to call an url that authenticate me and return a json object that contains my session_id.
I don't know if it is the correct way but whatever i don't know how to do that with zfcUser.
David
Next, i will be able to store this session_id into Shared Preferences storage.
First of all sorry for my English.
In my application i need almost the same.
Ok. So in yoursite.com/module/YourModuleName/Module.php do:
use YourModuleName\Model\YourModuleName;
use YourModuleName\Model\YourModuleName;
class Module {
public function onBootstrap(MvcEvent $e) {
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
$model = new OrdersManager();
if (!$auth->hasIdentity()) {
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($app, $sm, $auth, $model) {
$match = $e->getRouteMatch();
// No route, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
$match = $e->getRouteMatch();
$matchParams = $match->getParams();
// $matchParams['hash'] == some url param
if (isset($matchParams['hash'])) {
$model->setDbAdapterColibo($sm->get('dbAdapter'));
$usersSqlObject = $model->getUsers();
$salt = md5('caw');
foreach ($usersSqlObject as $key => $user) {
$hash = hash('sha256', $salt.$param1.$user['user_id']);
if ($hash == $matchParams['hash']) {
$authAdapter = $sm->get('ZfcUser\Authentication\Adapter\AdapterChain');
$request = $app->getRequest();
$request->getPost()->set('identity', $user['email']);
// You may use user password to auth user
$request->getPost()->set('credential', $user['user_id']);
$result = $authAdapter->prepareForAuthentication($request);
$auth->authenticate($authAdapter);
// do your staff with session or other.
// after this you will be redirect to page from where query was
break;
}
}
}
});
}
}
}
Don`t forget about yoursite.com/module/YourModuleName/config/module.config.php
You need to add route with your URL param, to receive it in $matchParams = $match->getParams();
In case I have describe you will be auth and immediately redirect to the site.
Example:
http://example.com/someController/someAction/param1/param2/hash...
the result will be auth and open page http://example.com/someController/someAction/param1/param2/hash...
Ok. This is what i need for my app. Hope this help.
P.S. Some ideas get from Zend Framework 2 - Global check for authentication with ZFCUser

Categories

Resources