Android PhoneGap app made in Eclipse won't run jQuery ajax call - ajax

I have a barebones index.html, Anddroid Phonegap project in Eclipse that will not execute jQuery Mobile ajax calls. LogCat displays the following messages and the app crashes
CordovaWebView: TIMEOUT ERROR!
CordovaWebViewClient.onReceivedError: Error code=-6 Description=The connection to the server was unsuccessful.
Interesting facts:
1.) Eclipse installs and runs the app fine if I comment out the ajax call. 2.) I use the same ajax pattern in an .apk that I get by processing an html-css-javascript app through PhoneGap Build, and it works fine.
Details:
In Eclipse Juno, I have an Android PhoneGap project (it uses the ADT and cordova-1.9.0.jar) with an index.html file which incorporates the following .js files in the following order:
<script type="text/javascript" src="Scripts/cordova-1.9.0.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
<script src="Scripts/temp.js" type="text/javascript"></script>
the temp.js file has this in it
$(document).ready(function(){
var theUrl = 'http://www.myDomain.biz/WebServices/gg.svc/';
console.log("theUrl + GetHelpFile = " + theUrl + "GetHelpFile");
$('div#divTarget').html("theUrl + GetHelpFile = " + theUrl + "GetHelpFile");
$.ajax({
type: "GET",
cache: false,
dataType: 'jsonp',
url: theUrl + "GetHelpFile",
contentType: "text/plain",
success: function (theJson) {
var help_file = $(theJson);
$('div#divHelpFile').html(help_file);
},
error: function ($theData) {
var tt = $theData;
alert(tt);
}
});
});
The project has
cordova-1.9.0.jar in its build path
an AndroidManifest.xml file that
has <application><activity>s for my .java file
android:name=".java_activity" and for
android:name="org.apache.cordova.DroidGap"
and all the <uses-permissions>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
the Run configuration I am using in Eclipse targets a 4.0 AVD and that all works fine.
When I comment out the ajax call, Eclipse creates the .apk file, opens the AVD, installs the app, and it runs fine. Also, I made a website in IIS for the same index.html file, in the same directory, and the page loads in the browser and the ajax runs fine.
I increased the timeout period and that did not help
super.setIntegerProperty("loadUrlTimeoutValue", 60000);
What do you think I need to do to get the ajax call to execute in my Eclipse-Android-PhoneGap project?
Thanks

You should use different type of ajax call:
$.get('http://yourdomain.com/index.php', function (data) {
alert(data);
});
phonegap android ajax call doesnt work
here is my solution.

Related

Change base path on VS publish

I have a blazorWASM project. While developing, I need index.html to have it's base path set to <base href="/" />, but when I use the built-in publish to file, the output is set to land directly into my PHP project which acts as a host that serves WASM static files, and needs this base path: <base href="/wwwroot/" />.
Is there a way to have them automatically switched so I do not keep forgetting to do so? Alternatively, how do I configure the project so that it will work while I debug it on IIS with the wwwroot base path?
You need to add a build task to your CSPROJ Blazor WASM.
Important note: you need Newtonsoft 13.0.1, System.Text.Json isn't supported.
<UsingTask TaskName="ReplaceBaseHRef" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
<ParameterGroup>
<InputFilename ParameterType="System.String" Required="true" />
<AppSettingsfile ParameterType="System.String" Required="true" />
<BaseHRefAttribute ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="$(NugetPackageRoot)\newtonsoft.json\13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Text" />
<Using Namespace="System.Text.RegularExpressions" />
<Using Namespace="Newtonsoft.Json" />
<Using Namespace="Newtonsoft.Json.Linq" />
<Code Type="Fragment" Language="C#">
<![CDATA[
var inputFile = File.ReadAllText(InputFilename);
var appsetting = File.ReadAllText(AppSettingsfile);
JObject appsettings = JObject.Parse(appsetting);
var baseHRef = appsettings[BaseHRefAttribute].Value<string>();
if (!string.IsNullOrEmpty(baseHRef)) {
Log.LogMessage( MessageImportance.High, baseHRef );
var outputFile = InputFilename;
var matchExpression = "\\<base\\ href=\\\"(.*)\\\"\\ \\/\\>";
var newBaseHRef = $"<base href=\"{baseHRef}\" />";
File.WriteAllText(
outputFile,
Regex.Replace(inputFile, matchExpression, newBaseHRef)
);
}
]]>
</Code>
</Task>
</UsingTask>
<Target Name="ReplaceBaseHRef" AfterTargets="Publish">
<ReplaceBaseHRef InputFilename="$(PublishDir)wwwroot\index.html" AppSettingsfile="$(PublishDir)wwwroot\appsettings.Production.json" BaseHRefAttribute="BaseHRef" />
</Target>
Now take your appsettings.Production.json and add the configuration setting as:
{
"BaseHRef": "/client/",
...
}
now launch the Publish (in folder, IIS or on Azure).
Your index.html will contain <base href="/client/" />.

How do I request permissions for my PhoneGap project built using PhoneGap Build?

I am trying to get started with Phonegap and Phonegap Build to create a html/jquery based Android app. Currently my app consists of one single html page that allows you to enter two numbers, those numbers are sent out to my server, and the response is displayed on screen. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>PoC</title>
<script src="JS/jquery.min.js"></script>
<script src="JS/jquery-ui.min.js"></script>
<script language="javascript" src="JS/date.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="css/style.css">
<script>
function doCalc() {
$.ajax({
url: "http://nightscapecreations.com/test.cfc?method=multNums&thisNum=" + $('#thisNum').val() + "&multBy=" + $('#multBy').val()
}).done(function( data ) {
data = data.trim();
if ($.isNumeric(data)) {
$('#resultDiv').html(data);
} else {
$('#resultDiv').html(data);
}
})
}
</script>
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
This is a test. Here, multiply some numbers:
<input id="thisNum" placeholder="5" onChange="doCalc();"> x
<input id="multBy" placeholder="3" onChange="doCalc();">
=
<div id="resultDiv">
</div>
<input type="button" value="Calculate" onClick="doCalc();" style="width:150px;">
</body>
</html>
Just a very messy test to see how this whole thing works. This functions when opened on a browser, or when run through the Phonegap app. However, when I upload this to Phonegap Build, download the apk, copy it to the device, and install it there, the div fails to populate.
I looked at my app and was surprised to see it listed with no permissions. I suspect this is the cause of the failure; the app cannot access the internet and so cannot get a response back from its ajax call. This would also explain why PB's Weinre debugging shows no targets. However, no matter what I do I cannot figure out how to get PB to assign permissions.
This is my current config:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.nightscapecreations.test"
version="1.0.0"
xmlns="http://www.w3.org/ns/widgets"
xmlns:gap="http://phonegap.com/ns/1.0">
<name>Test</name>
<description>
A PoC app
</description>
<author email="xxxxxxxxxxxx#hotmail.com" href="http://phonegap.com">
My Name
</author>
<content src="index.html" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
<preference name="orientation" value="portrait"/>
<preference name="fullscreen" value="false"/>
<preference name="permissions" value="none"/>
<feature name="http://api.phonegap.com/1.0/network"/>
<plugin name="cordova-plugin-network-information" source="npm" spec="~1.2.0" />
</widget>
There's a lot in there because I've been going through countless iterations of trial and error with stuff pulled from all over SO and various blogs. I have tried with and without the preference tags, the feature tag, the plugin tag, and much more, but no permissions are ever requested by the app.
I also tried adding a security policy as suggested in another post, but without success:
<meta http-equiv="Content-Security-Policy"
content="default-src *;
style-src 'self' 'unsafe-inline' 'unsafe-eval';
script-src 'self' 'unsafe-inline' 'unsafe-eval';">
How do I insure that my app has sufficient privileges to get data from my server?

Android app not permitting cleartext traffic inspite of adding xml permissions

I'm trying to access a development server API using nativescript-vue. I have added all the possible permissions in the android manifest, but it's giving the error: JS: Error: java.io.IOException: Cleartext HTTP traffic to url not permitted
Here is my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:usesCleartextTraffic="true"
android:name="com.tns.NativeScriptApplication"
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:cleartextTrafficPermitted="true"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="#xml/network_security_config"
android:theme="#style/AppTheme">
Here is the network_security_config.xml file:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">192.168.xxx.xxx</domain>
</domain-config>
</network-security-config>
And here is the Nativescipt-vue code:
httpModule.request({
url: "http://192.168.XXX.XXX:XXXX/func",
method: "POST",
headers: { "Content-Type": "application/json" },
content: data
}).then((response) => {
const result = response.content.toJSON();
}, (e) => {
console.error(e);
});
For those who face the same issue, tns platform remove android and tns platform add android worked for me. It started reading the updated manifest after this.
Go in to App_Resources -> Android -> src\main -> AndroidManifest.xml add android:usesCleartextTraffic="true" go to the application xml section then do a tns update resources cmd.

can't initialize speechRecognition on cordova

I have an app written in Keno UI (Telerik). I'm using build.phonegap.com to build runtime for my app, using cordova and Kendo. I'm stuck on getting the speechrecognition plugin to initialize. I'm sure it's something stupid but I'm not sure what it is.
Below is a copy of my config.xml file:
<?xml version='1.0' encoding='utf-8'?>
<widget id="ca.xyz.mmb" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>mmb</name>
<description>
Integrated Mobile Billing for XYZ Customers
</description>
<author email="support#xyz.ca" href="http://xyz.ca">
Go Team
</author>
<content src="index.html" />
<plugin name="cordova-plugin-compat" spec="^1.2.0" />
<plugin name="cordova-plugin-file" spec="^4.3.3" />
<plugin name="cordova-plugin-speechrecognition" spec="1.2.0" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
<engine name="ios" spec="^4.3.1" />
</widget>
Below is a copy of the relevant portion of the build:
Build Date: 2018-10-16 05:38:36 +0000
--------------------------------------------------------------------------------
PLUGIN OUTPUT
--------------------------------------------------------------------------------
Fetching plugin "cordova-plugin-compat#^1.2.0" via npm
Installing "cordova-plugin-compat" at "1.2.0" for android
Fetching plugin "cordova-plugin-file#^4.3.3" via npm
Installing "cordova-plugin-file" at "4.3.3" for android
Plugin dependency "cordova-plugin-compat#1.2.0" already fetched, using that version.
Dependent plugin "cordova-plugin-compat" already installed on android.
The Android Persistent storage location now defaults to "Internal".
Please check this plugin's README to see if your application needs any changes in its config.xml.
If this is a new application no changes are required.
If this is an update to an existing application that did not specify an "AndroidPersistentFileLocation" you may need to add:
"<preference name="AndroidPersistentFileLocation" value="Compatibility" />"
to config.xml in order for the application to find previously stored files.
Fetching plugin "cordova-plugin-speechrecognition#1.2.0" via npm
Installing "cordova-plugin-speechrecognition" at "1.1.2" for android
--------------------------------------------------------------------------------
PROJECT PROPERTIES
Below is the initalization code for the program.
(function () {
var bootstrap = function () {
$(function () {
alert("running bootstrap");
app.mobileApp = new kendo.mobile.Application(document.body, {
transition: 'slide',
skin: 'flat',
initial: 'components/home/view.html',
statusBarStyle: 'black-translucent',
layout: 'main'
});
alert("speech init "); //this is the last alert that pops up
window.plugins.speechRecognition.isRecognitionAvailable(
function(result) {
useSpeech = result ; alert("speech");
},
function(err) {
useSpeech = false; alert(err);
}
);
alert("done speech init");
});
};
bootstrap();
The place where I try to run isRecognitionAvailable is where it fails. I'm not sure why. I've tried putting in an alert for window.plugins just to see what it says but that always comes back undefined. A search on google implies that that is normal, so that doesn't help me much.

Xamarin - Fix 'Unfortunately, app has stopped' error on boot completed

I have created an app that calls boot completed class every time the phone restart. But my issue
is that I get a message that says 'Unfortunately, the app has stopped' every time I restart the phone, especially on older phones like OS 4.4.2. What could cause this issue?
My code :
Manifes.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="mypackagename" android:versionCode="1" android:versionName="1.0" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application android:allowBackup="true" android:label="#string/app_name" android:icon="#drawable/shortcut_icon">
<service android:enabled="true" android:name=".AppService" />
<receiver android:name=".RebootListener" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
Boot completed class
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
public class RebootListener : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context, typeof(AppService));
context.StartService(serviceIntent);
}
}
The issue persists even if I comment out the code in the OnReceive method. I presume the problem might be in the manifest file. If I remove the boot completed code in the manifest file I stop receiving this error message.
Remove the receiver from your manifest:
<receiver android:name=".RebootListener" android:enabled="true" android:exported="true">
<intent-filter>
~~~~
</intent-filter>
You have applied the BroadcastReceiver attribute to your BroadcastReceiver subclass and thus the Xamarin.Android build process will create this in your manifest automatically using a MD5-based Java class name (which will not be just .RebootListener)

Resources