When I use https://build.phonegap.com/ to build my application in android, my code to process the detection of the back button does not work.
Though I have used the following code to do it :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.1.min.css">
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery210.js"></script>
<script type="text/javascript" src="js/engine2.js"></script>
<script type="text/javascript" src="js/jqm141.js"></script>
<script type="text/javascript">
function onLoad(){
document.addEventListener('deviceready', function() {
navigator.splashscreen.show();
document.addEventListener("backbutton", ShowExitDialog, false);
}, false);
}
function ShowExitDialog() {
if (navigator.notification) {
navigator.notification.confirm(
("Are you sure ?"),
alertexit,
'Exit',
'Yes,No'
);
}
}
function alertexit(button){
if(button=="1" || button==1){
navigator.app.exitApp();
}
}
</script>
</head>
<body onLoad="onLoad()">
...
</body>
</html>
I get when pressing the back button, my application does not respond to anything. How do I add a detection function to Back button??
Use this simple code...
document.addEventListener("deviceready", appReady, false);
function appReady()
{
document.addEventListener('backbutton', function(e){
if (confirm("Press a button!"))
{
alert("You pressed OK!");
navigator.app.exitApp();
}
else
{
alert("You pressed Cancel!");
}
}, false);
}
Related
I started with Ionic and I made some first app, and that app works great on browser (windows 8 PC), but when I build app and try on the phone doesn't want to show map. Location as a number I can get on the phone too, but position on map I can't. Can anyone knows why?
index.html
<!DOCTYPE html>
<html>
<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" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body ng-app="inception">
<ion-nav-view></ion-nav-view>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-material/dist/ionic.material.min.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="app/application.js"></script>
<script src="app/controllers/mainController.js"></script>
<script src="app/controllers/locationController.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDVYeH02dc5EyoYaqpYSFsogSlkOx2S2o4&sensor=true"></script>
</body>
</html>
application.js
angular.module('inception', ['ionic','ionic-material','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
controller: 'locationController',
controllerAs:'locCtr',
templateUrl: 'app/views/location.html'
})
;
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/home');
});
controller
(function() {
'use strict';
angular
.module('inception')
.controller('locationController', locationController);
locationController.$inject=['$cordovaGeolocation','$http'];
function locationController($cordovaGeolocation,$http) {
var vm = this;
vm.locationOn = false;
vm.showSpinner = false;
vm.getMaps = getMaps;
function getMaps() {
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
vm.map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce(vm.map, 'idle', function(){
var marker = new google.maps.Marker({
map: vm.map,
animation: google.maps.Animation.DROP,
position: latLng
});
});
}, function(error){
console.log("Could not get location");
});
}
}
})();
view
<ion-header-bar class="bar bar-header bar-calm">
<h1 class="title text-center">Test</h1>
</ion-header-bar>
<ion-content class="has-header">
<div class = "row colors-back">
<div class = "col col-100">
<button class="button button-block button-balanced" ng-click="locCtr.getMaps()">
Get the map
</button>
<div id="map"></div>
</div>
</div>
</ion-content>
I am learning to develop mobile app using Phonegap and jquery mobile.
I have the main page with a list (index.html).
If user taps on an item, it should go on the next page.
Now this next page takes the id of the item, and the next page (a separate html file, second.html) contains the details related to this item.
So I need to know the id of the item tapped on the main page, and this second.html should display data accordingly.
What I want to know is, what do I use to pass the id from main page to second page? I am currently trying to pass data by using GET parameter (second.html?id=xyz), but don't know how to catch it on the second page.
I also read a method using localstorage, But i am not sure if that is a good idea, considering this will go on with the user going to third page, fourth page, and so on. so there'll be a lot of data saving into the local storage.
First page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" type="text/css" href="js/Jquery/jquery.mobile-1.4.5.css" />
<title>Restaurant App</title>
<script type="text/javascript" src="js/configs/server.js"></script>
<script type="text/javascript" src="js/Jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/Jquery/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div data-role="page" id="local">
<div data-role="main" class="ui-content">
<h2> Nearby Restaurants</h2>
<ul data-role="listview" data-inset="true" id="nearbyrestaurs">
</ul>
<script type="text/javascript">
var li = "";
$.getJSON(hostname + "/restaurants/?format=json", function(data) {
$.each(data, function(item, value) {
li = "<li><a rel=external href='menu.html?restid=" + value["id"] + "'>";
li += "<img src='";
li += hostname;
li += value["dp"];
li += "' class='ui-li-icon'>";
li += value["name"]
li += "</a></li>";
$("#nearbyrestaurs").append(li).listview('refresh');
});
})
</script>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" type="text/css" href="js/Jquery/jquery.mobile-1.4.5.css" />
<title>Restaurant Menu</title>
<script type="text/javascript" src="js/configs/server.js"></script>
<script type="text/javascript" src="js/Jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/Jquery/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div data-role="page" id="menupage">
<script type="text/javascript">
</script>
<div data-role="main" class="ui-content">
<h2> Menu</h2>
<ul data-role="listview" data-inset="true" id="Menus">
</ul>
<script type="text/javascript">
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(location.search);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
var li = "";
restid = $.urlParam('restid');
$.getJSON(hostname + "/menus/?format=json&restid=" + restid, function(data) {
$.each(data, function(item, value) {
li = "<li><a href='";
li += "#"
li += "' class='ui-li-icon'>";
li += value["name"];
li += "</a></li>";
$("#Menus").append(li).listview('refresh');
});
})
</script>
</div>
</div>
</body>
</html>
You can use location.search:
var params = location.search;
Params will have ?id=xyz. After that you can parse the string to obtain what you want.
Here is a related question :
Passing Data between pages with JQuery Mobile
You have a function like this already:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Usage:
var yourId = getParameterByName('Id');
Maybe, your specific case could be:
$.getJSON(hostname + "/menus/?format=json&restid=" + $.urlParam('restid'), function(data) {
Or possibly:
$.getJSON(hostname + "/menus/?format=json&restid=" + getParameterByName('restid'), function(data) {
I am trying to get ng-views to work in android phoneapp app. I get the following
error when I trying to navigate to one of the views via hyperlink.
"Origin is not allowed by Access-Control-Allow-Origin"
I have tried modifying the the cordova,xml in the res folder with no luck.
From
<access origin="http://127.0.0.1*"/> <!-- allow local pages -->
To
<access origin="*"/>
Any advice is appreciated, below is the code.
Thanks.
HTML:
<html ng-app="AngApp">
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Minimal AppLaud App</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="angular.js"></script>
<script type="text/javascript" charset="utf-8" src="app.js"></script>
<script type="text/javascript" charset="utf-8">
var onDeviceReady = function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
// The message from the service is appearing, so Angular seems
// to be working fine without having to bootstrap it.
//angular.bootstrap(document, ['AngApp']);
};
function init() {
document.addEventListener("deviceready", onDeviceReady, true);
}
</script>
</head>
<body onload="init();" id="stage" class="theme">
<h2>Angular App</h2><br/>
View1
View2
<hr/>
<div data-ng-controller="MainCtrl">
<p>{{Message}}</p>
<input type="text" data-ng-model="Message"/>
</div>
<hr/>
<div data-ng-view></div>
</body>
</html>
APP.JS:
var angApp = angular.module('AngApp',[]);
angApp.config(function ($compileProvider){
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
});
angApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: TestCtrl1,
templateUrl: 'view1.html'
})
.when('/view', {
controller: TestCtrl2,
templateUrl: 'view2.html'
});
});
angApp.factory('myService',function(){
return 'I am a service';
});
function MainCtrl($scope, myService){
$scope.Message = 'This is the main controller. '+ myService;
}
function TestCtrl1($scope){
$scope.Message = 'This is controller 1.';
}
function TestCtrl2($scope){
$scope.Message = 'This is controller 2.';
}
You are missing a # sign there in href="#/view".
I am new to programming phonegap apps. I have proved one simple phonegap app example and works fine on a Samsung Galaxy Mini, but doesn't in the Android emulator. The thing is, I want to show text when I click on a specific button inside the html.
App code is shown in below:
import android.os.Bundle;
import org.apache.cordova.*;
public class cordovaExample extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
MyClass js = new MyClass(this,appView);
appView.getSettings().setJavaScriptEnabled(true);
appView.addJavascriptInterface(js, "JS");
super.loadUrl(Config.getStartUrl());
}
}
public class MyClass
{
private WebView mAppView;
private DroidGap mGap;
Activity activity;
public MyClass(DroidGap gap, WebView view)
{
mAppView = view;
mGap = gap;
}
public String getText()
{
return "Hello World";
}
}
HTML code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script type="text/javascript" src="cordova-2.5.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
function Showessage()
{
var element = document.getElementById('time');
element.innerHTML = 'First Message :'+ window.JS.getText() + '<br />';
//alert('hello');
}
</script>
</head>
<body>
<div class="app">
<h1 class="event received" >Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received" id ="time" onclick="Showessage()">Device is Ready</p>
</div>
</div>
</body>
</html>
you have not to load corodova.X.X.js just the cordova.js script.
so the inclusion should be:
<script type="text/javascript" src="cordova.js"></script>
<!--- NOT <script type="text/javascript" src="cordova-2.5.0.js"></script> -->
I'm trying to call a service using jsonp on the andriod emulator:
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
receivedEvent: function(id) {
console.log('Received Event: ' + id);
$.ajaxSetup ({
cache: false
});
$.ajax({
type: "GET",
url: "http://10.0.2.2/uk-en/login/user",
dataType: "jsonp",
contentType: "application/json",
success: function(xml){
$("#result").html('123');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#result").html('XMLHttpRequest = ' + JSON.stringify(XMLHttpRequest) + ", textStatus = " + textStatus + ', errorThrown = ' + JSON.stringify(errorThrown));
}
});
}
I'm doing this on the HelloWorld app create following documentation on the phonegap site. My index.html is similar to this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>Hello World</title>
</head>
<body>
<div class="app">
<div id="result">
</div>
</div>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
This is the error I receive although this works from Firefox on my local machine:
XMLHttpRequest = {"READYSTATE":4,"STATUSTEXT":"SUCCESS"},TEXTSTATUS = PARSERERROR, ERRORTHROWN = {"MESSAGE":JQUERY1830456564654_32131 WAS NOT CALLED", "STACK":"ERROR:JQUERY1830456564654_32131 WAS NOT CALLED"\N AT FUNCTION.ERROR(http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js:2:13215)
Anyone able to help please?
JSONP requires that the response be wrapped in some kind of callback function.
This is all assuming you're grabbing the content from another domain. If so, you're limited by the same origin policy:
So the server should respond with:
urFunction({....});