Connection and testing of SQLite with ionic framework - android

hello I am working on an android project i was trying to connect to a prepopulated SQLite database on my windows machine..but im unable to go about it.
I also want to know if i can test on windows machine or it is necessary to connect to a android device to test because im not able to see any output on the emulator.
Please help .Thanks
enter code here
<!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></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic DataBase</h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController">
<button class="button" ng-click="SelectAll()">select</button>
<button class="button" ng-click="insert()">INSERT</button>
</ion-content>
</ion-pane>
</body>
</html>
enter code here
app.js
var example = angular.module('starter', ['ionic', 'ngCordova'])
var db = null;
example.run(function ($ionicPlatform,$cordovaSQLite) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
//window.Plugin.sqlDB.copy("newdata.db"), function ()
{
db = $cordovaSQLite.openDatabase("newdata.db");
//}, function (error) {
db = $cordovaSQLite.openDatabase("newdata.db");
}
});
});
example.controller("ExampleController", function ($scope, $cordovaSQLite) {
$scope.SelectAll = function() {
var query = "select ID, Dept from Department";
$cordovaSQLite.execute(db, query, []).then(function (res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
}
}
console.log("selected-> " + res.rows.item(i).ID + " " + res.rows.item(i).Dept);
}, function (err) {
console.error("No result found");
});
}
});
example.controller("ExampleController", function($scope, $cordovaSQLite) {
$scope.insert = function (Dept) {
var query = "INSERT INTO Department (Dept) VALUES (Finance)";
$cordovaSQLite.execute(db, query, [Dept]).then(function (res) {
console.log("INSERT ID -> " + res.insertId);
}, function (err) {
console.error(err);
});
}
});
above is the code used in my project.

cordoba-sqlite-storage doesn't support using an existing database. You need: https://github.com/litehelpers/cordova-sqlite-ext
run the following in your project's folder:
ionic plugin remove cordova-sqlite-storage
ionic plugin add cordova-sqlite-ext

Related

How to get User data (Public profile and Email ) In ionic framework

I am working on Ionic Mobile Application. After Creating Facebook Login button(Working fine) i want to get User data (Public profile and Email for my database.
My Index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/angular-sanitize/angular-sanitize.min.js"></script>
<script src="js/ng-cordova.min.js"></script><script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
Controller.js
.controller('login',['$scope','myService','$location','$state','$timeout',function($scope,myService,$location,$state,$timeout)
{
$scope.fbLogin = function ($cordovaOauth,$http) {
facebookLogin(window.cordovaOauth, window.http);
console.log(fbLogin);
}
}])
app.js
var app = angular.module('starter', ['ionic', 'starter.controllers','starter.services','ngSanitize', 'ngCordova', 'ngCordovaOauth']);
Please tell me where i am doing wrong.
And Sometimes i Get $cordovaOauth error.
Modular is not Injected.
function login(){
facebookLogin(window.cordovaOauth, window.http);
}
function facebookLogin($cordovaOauth, $http)
{
$cordovaOauth.facebook("1633195863589792", ["email", "public_profile"], {redirect_uri: "http://localhost/callback"}).then(function(result){
displayData($http, result.access_token);
}, function(error){
alert("Error: " + error);
});
}
function displayData($http, access_token)
{
$http.get("https://graph.facebook.com/v2.2/me", {params: {access_token: access_token, fields: "name,gender,location,picture", format: "json" }}).then(function(result) {
var name = result.data.name;
var gender = result.data.gender;
var picture = result.data.picture;
}, function(error) {
alert("Error: " + error);
});
}

Not asking share your location in worklight hybrid app

The worklight hybrid app is not asking share your location. Without asking it is showing some other location. What can i do for this? Please tell me the solution.
This is my total code
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Go2needs</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
window.$ = window.jQuery = WLJQ;
function wlCommonInit() {
}
function getGeo() {
alert();
/* WL.Device.Geo.acquirePosition(positive, negative, {
enableHighAccuracy: true,
});
alert(); */
if (navigator.geolocation) {
alert('if');
navigator.geolocation.getCurrentPosition(function(position) {
//alert(position.coords.latitude);
//alert(position.coords.longitude);
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
alert('geo');
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1]);
alert(results[1].formatted_address);
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
alert('end');
}
}
/* function positive(data) {
alert();
alert(JSON.stringify(data));
}
function negativa(data) {
alert();
alert(JSON.stringify(data));
} */
</script>
</head>
<body onload="WL.Client.init({})">
<input type="button" value="Click" onclick="getGeo()" />
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
The way you are implementing this is very strange; it is as if you're following tutorials from Worklight 4.x or 5.x... very old.
Try this:
AndroidManifest.xml
Add required permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
index.html
The head should be like this:
<head>
<meta charset="UTF-8">
<title>index</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!-- <link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png"> -->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
And the body:
<body style="display: none;">
<h1>Googlel Maps - show my position</h1>
<div id="map-canvas"></div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
main.js:
var myLat;
var myLong;
function wlCommonInit(){
navigator.geolocation.getCurrentPosition(setPositionCoords, errorSettingCoords);
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLat, myLong),
map: map,
title:"Hey Me!"
});
}
function setPositionCoords(position) {
myLat = position.coords.latitude;
myLong = position.coords.longitude;
}
function errorSettingCoords() {
alert ("Failed setting coordinates.");
}

Web API call failed in device mode but working in emulater in Cordova

In my project I have deployed my web api in cloud server and getting the data from that service. In ripple emulator it is working perfectly. But when I debuging in device mode (Android Tab) it is enable to call the service.It didn't show any specific error message also.
here in my index.html page
<!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></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<script src="lib/ng-cordova.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!--angularJS local storage-->
<script src="js/angular-messages.min.js"></script>
<script src="js/angular-local-storage.min.js"></script>
<!-- your app's js -->
<script src="app/app.js"></script>
<script src="app/services/authIntercepterService.js"></script>
<script src="app/services/productService.js"></script>
<script src="app/controllers/mainAppController.js"></script>
<script src="app/controllers/productsController.js"></script>
</head>
<body ng-app="app">
<ion-nav-view></ion-nav-view>
</body>
</html>
and Here is product service
app.factory('productService', ['$http', '$q', 'localStorageService', 'ngAuthSettings', function ($http, $q, localStorageService, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var productServiceFactory = {};
var _getAllDishCategories = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: serviceBase + "api/Product/GetAllDishCategories"
}).success(function (response) {
deferred.resolve(response);
}).error(function (err, status, header, config) {
deferred.reject(err);
});
return deferred.promise;
};
var _getProductById = function (productId) {
var deferred = $q.defer();
$http({
method: 'GET',
url: serviceBase + "api/Product/GetProductById",
params: {
productId: productId
}
}).success(function (response) {
deferred.resolve(response);
}).error(function (err, status, header, config) {
deferred.reject(err);
});
return deferred.promise;
};
productServiceFactory.getAllDishCategories = _getAllDishCategories;
productServiceFactory.getProductById = _getProductById;
return productServiceFactory;
}]);
Here is my Web API controller
using FandBClassLibrary;
using FandBViewModel.Product;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace FandBWebAPI.Controllers
{
[RoutePrefix("api/Product")]
public class ProductController : ApiController
{
#region Member variable
private IProductManager productManager;
#endregion
#region Constructor
public ProductController()
{
}
public ProductController(IProductManager productManager)
{
this.productManager = productManager;
}
#endregion
#region Post Methods
[HttpGet]
[Route("GetAllDishCategories")]
public List<DishCategoryViewModel> GetAllDishCategories()
{
var dcList= productManager.GetAllDishCategories();
return dcList;
}
[HttpGet]
[Route("GetProductById")]
public ProductViewModel GetProductById(string productId)
{
var productdetails = productManager.GetProductById(productId);
return productdetails;
}
#endregion
}
}
Here I have enable CROS in startup class
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(FandBWebAPI.Startup))]
namespace FandBWebAPI
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
}
}
Could someone help me to resolve this issue please?
Thanks,
Erandika
I had to install the whitelist plugin. After that it start to work. You can use following command to install the plugin. To do that in command prompt go to your project folder and execute following command.
cordova plugin add cordova-plugin-whitelist
More info please refer this URL
Thanks,
Erandika.
If you Web API is hosted locally it is hard to reach it from your device.
The best thing you could to is to put your Web API on an online domain, so you can approach it via WWW.
As example:
What your probably using at the moment is: http://localhost:port/api/movies
If you have a website and an app with permission to the internet you can do: http://yourwebsite.com/api/movies.
For more question send me a message.
Goodluck!

Onsen - Cordova - AngularJs module is not available

I've an hybrid app for android, i'm using cordova and onsen + angular js.
This is my index.html file:
<html lang="en" ng-app="AppModel">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>AppModel</title>
<!-- <link rel="stylesheet" href="css/plugins.css"/> -->
<link rel="stylesheet/less" href="css/plugins.less"/>
<link rel="stylesheet" href="lib/onsen/css/onsenui.css">
<link rel="stylesheet" href="lib/onsen/css/onsen-css-components.css">
<link rel="stylesheet/less" href="css/app.less"/>
<link rel="stylesheet/less" href="css/base-layout.less"/>
<script src="css/less.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script src="js/lodash_3.2.0.min.js"></script>
<script src="lib/onsen/js/angular/angular.js"></script>
<script src="js/angular-google-maps_2.0.12.min.js"></script>
<script src="lib/onsen/js/angular/angular-touch.js"></script>
<script src="lib/onsen/js/onsenui.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/plugins.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="js/appStart.js"></script>
<script src="js/data/data.js"></script>
<script src="js/angularApp/controllers.js"></script>
<script src="js/angularApp/directives.js"></script>
<script src="js/angularApp/filters.js"></script>
</head>
<body >
<ons-sliding-menu
menu-page="modules/core/menu.html" main-page="modules/account_profile/login.html" side="left"
var="menu" type="reveal" max-slide-distance="260px" swipable="true" swipe-target-width="50">
</ons-sliding-menu>
</body>
</html>
This is the appStart.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 explicity call 'app.receivedEvent(...);'
exitFunction : function(){
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
ons.setDefaultDeviceBackButtonListener(function() {
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
});
/*
// Open any external link with InAppBrowser Plugin
$(document).on('click', 'a[href^=http], a[href^=https]', function(e){
e.preventDefault();
var $this = $(this);
var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), target);
});
*/
$(document).on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
//var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), "_system");
});
},
// 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);
}
};
(function() {
var app = angular.module('AppModel', ['onsen', 'angular-carousel', 'uiGmapgoogle-maps'])
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|mailto|tel|geo):/);
}
]);
document.addEventListener('deviceready', function() {
angular.bootstrap(document, ['AppModel']);
}, false);
})
And data.js, controller.js, filter.js, directive.js are all like this:
var app = angular.module('AppModel'); //this is the first line in each file
app.factory('MenuData', function(){ [...]
But when i launch the app in google chrome, the console says:
Uncaught Error: [$injector:nomod] Module 'AppModel' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.10/$injector/nomod?p0=AppModel
This message appears for the files data.js, controller.js, filter.js, directives.js due to the first line of each file.
I don't know what to do. Can someone help me?
Doesn't look like you're executing the line where the app module is created.
You must run the line
angular.module('appName', [dependencies]);
before you created your controllers and services, like the error message says.
Are you calling the anonymous function that creates the module? Just add an empty parenthesis and it should run:
(function() {
var app = angular.module(...
})();
As the error message says, you must specify the dependencies as the second argument. If none is needed, then pass an empty array.
change
var app = angular.module('AppModel'); //this is the first line in each file
to
var app = angular.module('AppModel', []); //this is the first line in each file
and run it again.
Additional information: https://docs.angularjs.org/api/ng/function/angular.module

Angular need page refresh to load new view

I am trying to develope an app using angular.js and phonegap. My problem is that I have set everything good in my router, but still new views are not loading, so in order to change the view after the route is changed you need to refresh.
Here is my index.html file
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0"/>
<!-- Use the .min version of bootstrap files in production -->
<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<title>Angular PhoneGap Sample</title>
</head>
<body>
<!-- The following tag is in place of ng-view to use the angular mobile view navigation framework
https://github.com/ajoslin/angular-mobile-nav
-->
<mobile-view/>
<!-- Comment out the following 2 lines to test on the browser-->
<script type="text/javascript" src="cordova-2.7.0.js"></script>
<script src="lib/index.js"></script>
<!-- In production use min versions -->
<script src="lib/jx.min.js"></script>
<script src="lib/angular.js"></script>
<script src="lib/angular-mobile.js"></script>
<script src="lib/mobile-nav.js"></script>
<script src="lib/jquery.min.js"></script>
<!-- // <script src="lib/angular-route.min.js"></script>
// <script src="lib/angular-resource.js"></script>
// <script src="lib/ui-bootstrap-tpls-0.11.0.min.js"></script> -->
<script src="app/app.js"></script>
<script src="app/main/mainController.js"></script>
<script src="app/about/aboutController.js"></script>
<script src="app/about/playController.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
And here is the app.js
'use strict';
function jsonp_callback(data) {
// returning from async callbacks is (generally) meaningless
console.log(data.found);
}
var myApp = angular.module('myApp', ['ajoslin.mobile-navigate', 'ngMobile']);
myApp.config(function ($compileProvider){
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
})
.when('/play', {
templateUrl: 'app/play/play.html',
controller: 'PlayCtrl'
})
.when('/settings', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
})
.when('/options', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'app/about/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
myApp.run(function($rootScope, $location){
// $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
// if(rejection === 'not-authorized'){
// $location.path('/');
// }
// if(rejection == 'authorized'){
// $location.path('/home');
// }
// });
var history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.history = history;
});
And I tried to change route both with a hyperlink href="#/play" and within the controller$location.path('/play');` but nothing works ;/
I think, nothing will work until you inject ngRoute. You have to add that file too in Index.html.
angular-route.js is now separate file. You manually have to inject that file in order to run your defined routes.
One more thing with 'a' html link tag you have to write href="#play"...
I'm not sure about mobile-view. so use ng-view if it doesnt work.
At the end I was able to get it running with angular-mobile, ngRoute, and no hrefs. Instead of them I used this function on ng-click:
$scope.slidePage = function (path,type) {
navSvc.slidePage(path,type);
};
with this service, of course:
myApp.factory('navSvc', function($navigate) {
return {
slidePage: function (path,type) {
$navigate.go(path,type);
},
back: function () {
$navigate.back();
}
}
});

Categories

Resources