Cordova android plugin unable to update JSON object - json

i have developed a cordova plugin for optical character recognition. I send image to android and the image processing part is done by the plugin and after processing the plugin returns the JSON object back to Cordova. The plugin is working fine for the first time only the data is received correctly but when i tried to process an image for second time the data returned by the plugin is correct but on cordova side the Json object is not updated it shows previous data.
try {
if (ACTION.equals(action))
{
Log.d("action name", action);
Log.d("json object", args.getString(0));
//JSONObject arg_object = args.getJSONObject(0);
this.callbackContext = callbackContext;
if(ACTION_CAMERA.equals(args.getString(0))){
Log.d("action name", "camera");
cordova.getThreadPool().execute(new Runnable() {
public void run() {
camera();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json)); // Thread-safe.
}
});
}
/*
* sending the JSON object containing OCR results and BASE64 encoded string to javaScript
*/
//callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
result = true;
Log.d("after results", "after results");
}
else{
callbackContext.error("Invalid action");
result = false;
}
return result;
}
catch(Exception e)
{
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
and my cordova code is
function onPhotoURISuccess(obj) {
alert(obj['all']);
// clear image div contents
$("#base64Image").empty();
$("#base64Image").attr('src', '');
var image = new Image();
image.src = 'data:image/png;base64,' + obj['imageBase64'];
$("#base64Image").append(image);
$('#base64Image').width();
}
// A button will call this function
function capturePhoto() {
var success = function(message) {
onPhotoURISuccess(message);
}
var failure = function() {
alert("Error calling OCR 1 Plugin");
}
OCRPlugin.greet("camera", success, failure);
}

Related

How to call a get REST API from a tvOS Application using Xamarin?

I am trying to call a get REST API from my tvOS application. Following is my code when tap the Button:
async void ButtonClicked(UIButton sender)
{
try
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("rest api url");
if (response.IsSuccessStatusCode)
{
var Response = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrWhiteSpace(Response.ToString()))
{
var category = JsonConvert.DeserializeObject<Videos>(Response.ToString());
Debug.WriteLine("count:>>" + category.webContentCategoryList.Count);
}
}
}
catch(Exception e)
{
Debug.WriteLine("Exception:>>"+e);
}
I have installed the system.net.http and newtonsoft.json nuget packages. But when I run the project the application showing Main.cs file like below screenshot:
Am I missing something in this?
UPDATE
I have added breakpoint for the first line inside ButtonClicked function. When I taps the Button, the application showing Main.cs file like above screenshot. It is not hitting the first line of ButtonClicked function.
So the issue is something else, I am not an expert in tvOS applications so I can't figure out. I have uploaded a sample project here.
I have fixed this issue by separating the service call on a new function like below, new function is the async method:
partial void ButtonClicked(UIButton sender)
{
LoadData();
}
async void LoadData()
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("service url");
if (response.IsSuccessStatusCode)
{
var Response = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrWhiteSpace(Response.ToString()))
{
var category = JsonConvert.DeserializeObject<Videos>(Response.ToString());
Debug.WriteLine("count:>>" + category.Count);
}
}
}
My XF Thread is here for more details.

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest'

I need to display hello world using servlet program in browser by Ajax call but on clicking button I am not to display it what could be reason of this error:
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/workspace/Poc_Ajax/WebContent/WEB-INF/HelloWorld'.
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "HelloWorld", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send();
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
</script>
</head>
<body>
<div>Getting Started with AJAX using JAVA: Hello World!</div>
<div id="hello"><button type="button" onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>
To run a servlet program you need to make an HTTP request to a web server that is configured to execute the servlet.
Your Ajax URL (as displayed in the error message) starts with file:// so you are trying to deal with a local file instead of a webserver.
Install a webserver (such as Tomcat). Load your HTML document from it. Make sure that "HelloWorld" is a relative URI from that HTML document to the servlet URL.

background Agent works fine in local environment but failed after app submission to app store

I have an wp8 app using PeriodicTask background Agent.
The task update the information of multiple live tiles,
using POST Client to get title and image url from my server to update the live tile.
Background agent works just fine in debugging and releasing mode. When the .xap file was deployed into my device using XAPDeployement tool, the background Agent also works perfectly.
However, it won't work after submitted to wp app store, no matter it's beta version or not.
If the app is downloaded from store, the background agent has never worked, and it is blocked by system after a few minutes.
How come it goes wrong since the XAP files are the same?
part of code:
public static Task<string> jsonPostClientTask(Dictionary<string, object> parameters, string url)
{
var results = new TaskCompletionSource<string>();
PostClient proxy = new PostClient(parameters);
try
{
proxy.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
string response = e.Result.ToString();
results.TrySetResult(response);
}
else
{
results.TrySetResult("");
results.TrySetException(e.Error);
}
};
proxy.DownloadStringAsync(new Uri(url));
}
catch
{
results.TrySetResult("");
}
return results.Task;
}
ScheduledAgent class:
protected override void OnInvoke(ScheduledTask task)
{
foreach (var tile in tileList)
{
string dataString = jsonPostClientTask(parameters, url);
//update tile in used
FlipTileData tileData = new FlipTileData()
{
BackContent = "string content",
WideBackContent = "string back content",
BackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
WideBackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
};
ShellTile primaryTile = ShellTile.ActiveTiles.First();
if (primaryTile != null)
primaryTile.Update(tileData);
}
}

Passing two URLS to AJAX and getting response in two divs

I am using AJAX and i have four URLS of HTML. I want to fetch this four urls using AJAX and want to load them in four different divs dynamically. Although i have written code to access one url. Code is here...
function load(url)
{
if (window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch (e) {req = false;}
} else if (window.ActiveXObject) {
// For Internet Explorer on Windows
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
req = false;
}
}
}
if(req) {
req.open('GET', url, false);
req.send(null);
}
}
load('<%=request.getScheme()%>://${domain}/car-rental/html/global/${siteLanguage}/terms/PrefMbrGlobalTermsMiddle-text.html');
function display(id)
{
var element = document.getElementById(id);
if (element && req)
{
// Synchronous request, wait till we have it all
element.innerHTML = req.responseText;
}
}
I want to do same type of logic to load four urls .. Please help me out...
What I understood from your code is load function you are using to make an ajax call. So what can do call load function as:
load("url1","target-div1");
load("url2","target-div2");
load("url3","target-div3");
load("url4","target-div4");
inside load on successful of AJAX set the content target-div with AJAX response.

Geolocation in Flash

I'm building a small web app in Flash. Is there a solution to get the geo-location of a user?
The easiest way is to interface with a JavaScript function.
In your HTML:
<script>
function getGEO()
{
// First check if your browser supports the geolocation API
if (navigator.geolocation)
{
//alert("HTML 5 is getting your location");
// Get the current position
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude
long = position.coords.longitude;
// Pass the coordinates to Flash
passGEOToSWF(lat, long);
});
} else {
//alert("Sorry... your browser does not support the HTML5 GeoLocation API");
}
}
function passGEOToSWF(lat,long)
{
//alert("HTML 5 is sending your location to Flash");
// Pass the coordinates to mySWF using ExternalInterface
document.getElementById("index").passGEOToSWF(lat,long);
}
</script>
Then, in your Application, once your map is ready, put this in a function:
//for getting a user's location
if (ExternalInterface.available)
{
//check if external interface is available
try
{
// add Callback for the passGEOToSWF Javascript function
ExternalInterface.addCallback("passGEOToSWF", onPassGEOToSWF);
}
catch (error:SecurityError)
{
// Alert the user of a SecurityError
}
catch (error:Error)
{
// Alert the user of an Error
}
}
Finally, have a private function ready to catch the callback.
private function onPassGEOToSWF(lat:*,long:*):void
{
userLoc = new LatLng(lat,long);
map.setCenter(userLoc);
}