(Changed based on the answers I've received, and to flush out what this is about, i.e. calling a REST service from PhoneGab mobile client to a server, so I've taken all out except calling a REST service)
Windows 7 64 bit Developer station, running on IPhone 5
I would be out most gratefull if someone had the time to help me here, - because I've no idea what is going on, - I've read all the questions about this, - and answers...
I've installed PhoneGap (192.168.1.50:3000) on my IPhone and PC as the back-end (running JBOSS for the REST services on port 8080, tested with postman through http://192.168.1.50:8080/chkin/parent/51/kids and not only localhost, i.e. you can call the same REST service through the browser of the mobile and I get a responds back)
I now get the event (alert("deviceReady")), but it does not call the server, - that could be a config.xml problem? I've just taken the config.xml file out of the box, when it was generated and added
<access origin=".*" />
<access origin="http://127.0.0.1"/> <!-- allow local pages -->
<access origin="http://192.168.1.50" subdomains="true"/>
Questions
Should config.xml be in the www folder one up? The folder structure when made by the phonegab-desktop looks like this (I copied into the www folder so it there two places, yes I know....):
.cordova
hooks
platforms
www
css
img
js
res
index.html
(config.xml)
plugins
config.xml
Content of the Config.xml:
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.phonegap.helloworld" version="1.0.0">
<name>test</name>
<description>Hello World sample application that responds to the deviceready event.</description>
<author href="http://phonegap.com" email="support#phonegap.com">PhoneGap Team</author>
<content src="index.html"/>
<preference name="permissions" value="none"/>
<preference name="orientation" value="default"/>
<preference name="target-device" value="universal"/>
<preference name="fullscreen" value="true"/>
<preference name="webviewbounce" value="true"/>
<preference name="prerendered-icon" value="true"/>
<preference name="stay-in-webview" value="false"/>
<preference name="ios-statusbarstyle" value="black-opaque"/>
<preference name="detect-data-types" value="true"/>
<preference name="exit-on-suspend" value="false"/>
<preference name="show-splash-screen-spinner" value="true"/>
<preference name="auto-hide-splash-screen" value="true"/>
<preference name="disable-cursor" value="false"/>
<preference name="android-minSdkVersion" value="14"/>
<preference name="android-installLocation" value="auto"/>
<gap:plugin name="org.apache.cordova.battery-status"/>
<gap:plugin name="org.apache.cordova.camera"/>
<gap:plugin name="org.apache.cordova.media-capture"/>
<gap:plugin name="org.apache.cordova.console"/>
<gap:plugin name="org.apache.cordova.contacts"/>
<gap:plugin name="org.apache.cordova.device"/>
<gap:plugin name="org.apache.cordova.device-motion"/>
<gap:plugin name="org.apache.cordova.device-orientation"/>
<gap:plugin name="org.apache.cordova.dialogs"/>
<gap:plugin name="org.apache.cordova.file"/>
<gap:plugin name="org.apache.cordova.file-transfer"/>
<gap:plugin name="org.apache.cordova.geolocation"/>
<gap:plugin name="org.apache.cordova.globalization"/>
<gap:plugin name="org.apache.cordova.inappbrowser"/>
<gap:plugin name="org.apache.cordova.media"/>
<gap:plugin name="org.apache.cordova.network-information"/>
<gap:plugin name="org.apache.cordova.splashscreen"/>
<gap:plugin name="org.apache.cordova.vibration"/>
..
<access origin="*" />
<access origin=".*" />
//<access origin="http://127.0.0.1"/> <!-- allow local pages -->
//<access origin="http://192.168.1.50" subdomains="true"/>
..
<plugin name="cordova-plugin-whitelist" version="1"/>
<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>
</widget>
File: Index.html
...
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
File: index.js:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
alert("deviceReady");
$.ajax({
type: 'GET',
url: 'http://192.168.1.50:8080/chkin/parent/51/kids',
//async: false,
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
alert("Works! " + JSON.stringify(data));
},
error:function(data){
alert("Bad thing happend! " + JSON.stringify(data));
}
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
I also figure out to use dataType: 'jsonp' instead of dataType: 'json' otherwise I could not get Ripple to call either
Finally I would like to know if there is any way I can see the log on the phone? That would be helpfull
Again thank you for you help!!!
PS: Just uploaded the file structure if there was something there:
enter image description here
setup your main js in an alternative way
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
// App code
}}
app.initialize();
and include the scripts at the bottom of the body
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/main.js"></script>
and remove
<script>
$(function(){
document.addEventListener("deviceready", onDeviceReady, true);
});
</script>
i maybe missing some markup as i have about 1k worth of lines of code where // App code is
if you want to debug the App on Android check here -- Android remote debugging for Phonegap app does not work
I've had many issues with Phonegap, switched to Cordova and many problems disappeared.
To get back to your problem, I had JavaScript errors which only appeared during deviceready.
Do you have a mechanism for checking for JavaScript Errors while testing on the phone?
I wrote this mini library to help me track Cordova Errors:
https://github.com/jVaaS/onerrorjs
Inside the error handler, you should do something like this (I have a <pre></pre> tag somewhere on my page to display errors):
jvaas.submitError = function (error) {
$("pre").text = JSON.stringify(error);
}
Then if you are error free on the Cordova side, you should check for cross-domain errors - when you normally run your code, you'd run it as http://localhost or http://localhost:8080, but when it's running via Cordova / Phonegap, it's actually running as file://somefile.html, so you should test your html running it directly as a file in your browser with your console open to see if using non-http protocols causes cross-domain errors.
If you've checked all those, we can look at further solutions.
There is kinder two problems that was wrong here
1) The first was the point made by Tasos, - it was the addEventListener, needed
2) The second is that Cordova/Phonegab is not "forgiven" I had made some stupid java scripts errors not picked up from the Ripple or Chrome, but I basically started all over and made something that worked using the alert command in phonegab to get out put, and then slowly adding stuff!
so I need to figure out to get logs out of PhoneGab, - but that can't be in this thread...
For logging/Debugging:
If you load you client phonegab project from the same server as the one where the rest services are then you can use Chrome with Ripple and it works, that gives a much better way of debug.
If you want to log it on the phone it's quite easy to setup please follow this for seting up weinre https://www.youtube.com/watch?v=xepgYpqj8ew
Notice for starting Weinre up locale you write:
weinre --httpPort 7777 --boundHost -all-
otherwise it won't listen to external connections!!!
Related
This question already exists:
What do I have to change to run a normal Ajax in PhoneGap?
Closed 2 years ago.
Hello i want to build a hybrid app out of my website code but the problem is i read Phonegap doesn't support my ajax request do you know any alternative and could you share it with me?
My Ajax request:
$.ajax({
type: "POST",
url: "http://quantivorquali.de/amk.Neusocken.php",
data:{nam_ersteller:nam_ersteller, punkte:punkte, text:text, benachrichtigung:benachrichtigung, status:status},
success: function(data){
window.location = "http://quantivorquali.de/amk.html";
}
})
Phonegap supports ajax requests but you will need to do the following.
Makesure your php files have the following line at the top of each php file - this allows the app to access to the php file:
header('Access-Control-Allow-Origin: *');
The success result in your script will redirect the app to an external website outside the app unless you use the relevant plugins for Phonegap.
You may need to add:
cordova-plugin-whitelist
cordova-plugin-inappbrowser
to your config.xml file along with
<access origin="*" />
<allow-navigation href="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<allow-navigation href="https://*.someURL.com/*" />
Does the following work?
hello.php:
<?php
header('Access-Control-Allow-Origin: *');
echo 'Hello World';
?>
Ajax:
$.ajax({
type: "POST",
url: "https://www.exampleURL.com/hello.php",
dataType:"html",
data:"some=string",
success: function(data){
alert(data)
}
})
I have created the ionic app , I am running the app in browser is working fine . but the same app I tried to run in mobile the AJAX call is not working. Before the ajax i made alert it is populated. Below is my code .
Code is,
$http({
method: 'POST',
//url: syncURL,
url:"http://45.xx.xxx:8080/MobileSync/SummaTest/update_SummaNoun",
data: surveyResultrecords,//surveyResultrecords
}).then(function(result){
console.log( "yay---" +JSON.stringify(result.data));
alert("yay");
alert("APTAM");
//$scope.SummaNoun.id = surveyResultrecords.id;
//var promise1 = imageUpload();
//console.log("PUSH completed ");
//alert("test---finished");
return "data Updated";//imageUpload();
}).then(function(ress){
console.log("PUSH completed ");
alert("push completed")
});
These are the cordova plugins i Installed ,
"cordovaPlugins": [
"cordova-plugin-camera",
"cordova-plugin-device",
"cordova-plugin-console",
"cordova-plugin-splashscreen",
"cordova-plugin-statusbar",
"ionic-plugin-keyboard",
"cordova-plugin-whitelist",
"cordova-plugin-file",
"cordova-plugin-file-transfer"
]
Config.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.Testcamera10008" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>testCamera</name>
<description>
An Ionic Framework and Cordova project.
</description>
<author email="you#example.com" href="http://example.com.com/">
Your Name Here
</author>
<content src="index.html"/>
<preference name="webviewbounce" value="false"/>
<preference name="UIWebViewBounce" value="false"/>
<preference name="DisallowOverscroll" value="true"/>
<preference name="SplashScreenDelay" value="2000"/>
<preference name="FadeSplashScreenDuration" value="2000"/>
<preference name="android-minSdkVersion" value="16"/>
<preference name="BackupWebStorage" value="none"/>
<preference name="SplashScreen" value="screen"/>
<feature name="StatusBar">
<param name="ios-package" value="CDVStatusBar" onload="true"/>
</feature>
<platform name="android">
<allow-intent href="market:*"/>
<allow-intent href="*"/>
<allow-navigation href="*"/>
<access origin="*"/>
<icon src="resources/android/icon/drawable-ldpi-icon.png" density="ldpi"/>
<icon src="resources/android/icon/drawable-mdpi-icon.png" density="mdpi"/>
<icon src="resources/android/icon/drawable-hdpi-icon.png" density="hdpi"/>
<icon src="resources/android/icon/drawable-xhdpi-icon.png" density="xhdpi"/>
<icon src="resources/android/icon/drawable-xxhdpi-icon.png" density="xxhdpi"/>
<icon src="resources/android/icon/drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
<splash src="resources/android/splash/drawable-land-ldpi-screen.png" density="land-ldpi"/>
<splash src="resources/android/splash/drawable-land-mdpi-screen.png" density="land-mdpi"/>
<splash src="resources/android/splash/drawable-land-hdpi-screen.png" density="land-hdpi"/>
<splash src="resources/android/splash/drawable-land-xhdpi-screen.png" density="land-xhdpi"/>
<splash src="resources/android/splash/drawable-land-xxhdpi-screen.png" density="land-xxhdpi"/>
<splash src="resources/android/splash/drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi"/>
<splash src="resources/android/splash/drawable-port-ldpi-screen.png" density="port-ldpi"/>
<splash src="resources/android/splash/drawable-port-mdpi-screen.png" density="port-mdpi"/>
<splash src="resources/android/splash/drawable-port-hdpi-screen.png" density="port-hdpi"/>
<splash src="resources/android/splash/drawable-port-xhdpi-screen.png" density="port-xhdpi"/>
<splash src="resources/android/splash/drawable-port-xxhdpi-screen.png" density="port-xxhdpi"/>
<splash src="resources/android/splash/drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi"/>
</platform>
</widget>
index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy">
<title>Testcamera</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script><script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<script src="app/js/app.js"></script>
<script src="lib/jquery/jquery-2.1.3.min.js"></script>
<script src="lib/ionic-datepicker/dist/ionic-datepicker.bundle.min.js"></script>
<script src="app/js/controllers/AplicationLevelCtrl.js"></script>
<script src="app/js/controllers/SummaTest.js"></script>
<script src="app/js/controllers/SummaNoun_Default_Activity.js"></script>
<body ng-app="Testcamera">
<ion-nav-view></ion-nav-view>
</html>
Chrome Inspecter Image
I installed the cordova-whitelist plugin also my cordova version 6.2.0 , ionic 1.7.16.
Why you don't have plug-ins declaration in your config.xml, for example:
<plugin name="cordova-plugin-whitelist" spec="~1.2.2" />
And you don't have this tag:
<access origin="*" subdomains="true" />
read here for more informations about it
Also, this post may help you. Good luck
First off, you don't need extra then in your code since it's not returning promise. It's just a string literal. Always handle error part of a promise.
Better version:
$http.post(url, data)
.then(function (res){ // handles response
console.log(res.data); // or execute success function
}, function (err){ // handles error
console.log(err); // or JSON.stringify(err) if it shows [object] on the console
});
Make sure all the plugins are there on platforms/(android/ios) run on the device.
After that, do ionic run android/ios --lc and see error logs on command line to see what went wrong.
This could be possible issue with white-listing. That's the reason the AJAX call may be working fine in browser and not in devices. You gotta use allow-intent attribute with proper settings for HTTP and HTTPS protocols in config.xml to get away from this problem.
Suggest you to check out this SO Post which has the desired settings to overcome this problem
Thanks for all the kind response guys , we found the issue followed #Italo Ayres his comment Remote Debugging Android Devices . we saw the log of our app and corrected the Error.
Because We tried Android Studio to see the logs but it doesn't shown that Ajax Call it shown only before the AJAX call logs .
We referred this Link to see the mobile Logs using Chrome .Please have a look in it . Its very Usefull. Remote Debugging Android Devices
I included the socialsharing plugin into config.xml as:
<gap:plugin name="nl.x-services.plugins.socialsharing" />
(using cordova v. 3.3.1)
In my html I include:
<script src="phonegap.js"></script>
or
<script src="cordova.js"></script>
Now when calling:
function shareReport() {
window.plugins.socialsharing.share(mytext);
}
by a button:
onclick="shareReport()"
the program stops suddenly and closes down.
("mytext" is a global variable that is populated with a text string containing html tags - this variable has a value at this point)
Any suggestions what is going wrong ?
Thank you in advance,
Chris
Social sharing Plugin will work as you expected so it looks like you missed something,
Check your XML for below fields,
<!-- for iOS -->
<feature name="SocialSharing">
<param name="ios-package" value="SocialSharing" />
</feature>
<!-- for Android -->
<feature name="SocialSharing">
<param name="android-package" value="nl.xservices.plugins.SocialSharing" />
</feature>
<!-- for Windows Phone -->
<feature name="SocialSharing">
<param name="wp-package" value="SocialSharing"/>
</feature>
AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check your Script,
<script type="text/javascript" src="js/SocialSharing.js"></script>
This is must,
<gap:plugin name="nl.x-services.plugins.socialsharing" version="4.0" />
Try a test drive,
<button onclick="window.plugins.socialsharing.canShareVia('com.apple.social.facebook', 'msg', null, null, null, function(e){alert(e)}, function(e){alert(e)})">is facebook available on iOS?</button>
Hope this helps.
OK, I figured it out.
You were right, the SocialSharing plugin works simply by including the line
<gap:plugin name="nl.x-services.plugins.socialsharing" />
into config.xml.
My problem came from unaccepted characters in the text that I sent for sharing which caused the program crash.
Thanks for every help !
Issue Solved. TIL i need to add a script link to Cordova in my html
I know the event is firing as my server shows the request to the link when I click on the button. It connects fine with chrome on my pc and tablet but the native app button won't open the system browser for me.
The link connects to a .apk download which the server is registering as requested when I press the button so the event handling is not the issue afaik. I've also tried '_blank' instead of system but still no joy
Any help would be much appreciated
Edit: Also tried navigator.app.loadUrl as per here
Edit Edit: Hmmmm, I tried inserting an ´alert("test");´ statement in the first line of the function and that's not firing... yet server of the target link is registering the requests.
The relevant patch of code is here:
Server.getUpdateInfo(getDevice()?getDevice():"Android", function (data) {
if(data.IsUpdate){
if(getDevice()){
$("#btnInstall").on("click", function(){
window.open($(this).data("url"),'_system');
});
}
else {
$("#btnInstall").closest(".ui-btn").hide();
}
}
});
Here is my config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
xmlns:android = "http://schemas.android.com/apk/res/android"
id = "com.blahblahblah"
version = "1.0.4">
<name>Server App</name>
<description>
jQuery Mobile interface for Server Admin
</description>
<author>
Firma GmbH
</author>
<access origin="*"/>
<feature name="http://api.phonegap.com/1.0/device" />
<feature name="http://api.phonegap.com/1.0/network"/>
<feature name="http://api.phonegap.com/1.0/notification"/>
<preference name="phonegap-version" value="3.1.0" />
<preference name="orientation" value="default" />
<preference name="target-device" value="universal" />
<preference name="fullscreen" value="false" />
<preference name="auto-hide-splash-screen" value="true" />
<plugin name="Notification" value="org.apache.cordova.Notification"/>
<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager" />
<plugin name="NetworkStatus" value="CDVConnection" />
</widget>
Ensure there's a link to the cordova script in your html file. No need to load the file yourself as phonegapp will build it.
I haven't been able to get a local sound playing using the Cordova Media plugin.
I have the right options in my platforms\android\res\xml\config.xml here...
<content src="index.html" />
<access origin="*" />
<preference name="loglevel" value="DEBUG" />
<feature name="App">
<param name="android-package" value="org.apache.cordova.App" />
</feature>
<feature name="Device">
<param name="android-package" value="org.apache.cordova.device.Device" />
</feature>
<feature name="File">
<param name="android-package" value="org.apache.cordova.file.FileUtils" />
</feature>
<feature name="Media">
<param name="android-package" value="org.apache.cordova.media.AudioHandler" />
</feature>
<feature name="SplashScreen">
<param name="android-package" value="org.apache.cordova.splashscreen.SplashScreen" />
</feature>
...and the permission option in my AndroidManifest.xml...
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
However when I try to play a sound I get nothing:
Note: I'm using Apache Cordova 3.3.0
Managed to figure it out in the end you have to reference the file paths relative to the window.location.pathname as when run through Apache Cordova the root is file:///android_asset/www/ so the sounds must be referenced like so /android_asset/www/path/to/a/sound.mp3.
Here's my full solution:
var audio = {
root: '',
localPath: '/assets/sounds/',
manifest: {
bang: 'bang.mp3',
boom: 'boom.mp3',
splat: 'splat.mp3',
splash: 'splash.mp3'
},
sounds: {},
parse: function () {
var p = window.location.pathname;
this.root = p.substring(0, p.lastIndexOf('/')) + this.localPath;
console.log(this.root);
for (var sound in this.manifest) {
var src = this.root + this.manifest[sound];
console.log('Getting sound: ' + src);
this.sounds[sound] = (typeof Media !== 'undefined') ? new Media(src) : new Audio(src);
console.log('Created sound:');
$('#sounds').append($('<li></li>').html(src));
}
}
};
audio.parse();
So for instance my index.html is in my root which is essentially ./ from my perspective (the www folder).
All my sounds are within two sub folders ./assets/sounds/.
When hosting the application on my PC window.location.pathname appears as /:
However when hosted on my mobile device it is:
After doing a bit of digging as to how the Media plugin goes about playing audio naively via Android's MediaPlayer, I see that for some unknown reason the following permissions are required in the \platforms\androidAndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
Internet Permission - If you are using MediaPlayer to stream network-based content, your application must request network access.
I can only guess that because you're trying to stream local media via a WebView it requires this permission to function correctly.
However it would have been nice to get a better error message than undefined maybe something like.
code: 1
message: Missing Android permission
Apache Cordova should have added this permission automatically when installing the plugin.
EDIT: Actually this is only a partial fix for accessing remote audio files I still have yet to get local files working.
Here is my code and it works. make sure to install the device plugin
if(selectedSoundOption === "Coins"){
var coin180Url = getMediaURL("sounds/coin180.mp3");
var coin180 = new Media(coin180Url, null, mediaError);
var coin360Url = getMediaURL("sounds/coin360.wav");
var coin360 = new Media(coin360Url, null, mediaError);
if(rotation.indexOf("360") > -1){
coin180.play();
}else{
coin360.play();
}
}
}
function mediaError(e) {
alert('Media error '+e);
}
function getMediaURL(s) {
if(device.platform.toLowerCase() === "android") return "/android_asset/www/" + s;
return s;
}
After adding following lines in android \platforms\androidAndroidManifest.xml, sounds is played.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
Thanks Joshua, you solution works out for me.