SlideShare a Scribd company logo
1
Creating a CRUD with Ionic – Part 1
Juliano Marcos Martins – juliano.jmm@gmail.com
http://jmmwrite.wordpress.com
2
SQLite
Is a software library that
implements a self-contained,
serverless, zero-configuration,
transactional SQL database
engine.
https://www.sqlite.org/
3
Local Storage
Can be used to store data, but
don't Assume that it will Always
Work In Your Hybrid App.
// example
localStorage.setItem('nome', 'Juliano');
var name = localStorage.getItem('nome');
console.log(name);
IOs and Android can clean it in
some situations.
4
Intro
We will create an application to
manage people from a table.
Its recommended that you already have basic concepts about Ionic and Mobile Development
before go ahead. For more intro material, check my blog:
http://jmmwrite.wordpress.com/
You can get the source code from this slides here →
https://github.com/julianommartins/ionicDataBase.git
5
Step by Step
● Create the project
ionic start ionicDataBase blank
6
Step by Step
● Enter in the project folder and Add platform:
ionic platform add android
7
Step by Step
● Add SQLite module (documentation: http://ngcordova.com/docs/plugins/sqlite/ ):
cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storage.git
8
Step by Step
● Go to http://ngcordova.com/docs/install/ and get the JS lib (download the zip file)
● Extract it and get ng-cordova.min.js , put this file in the JS folder of your application
* You can also use bower to get ng-cordova
9
Step by Step
● Open your index.html file and import ng-cordova there by adding the folowing line
BEFORE cordova import:
<script src="js/ng-cordova.min.js"></script>:
10
Step by Step
● Open your app.js file and inject ngCordova module:
This will make module work!
11
Step by Step – index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DB Example</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.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">Pessoas</h1>
</ion-header-bar>
<ion-content ng-controller="DBController">
<button class="button" ng-click="insert('Juliano','Martins')">Insert</button>
<button class="button" ng-click="select('Martins')">Select</button>
Resultado: {{mensagemFinal}}
Resultado: {{resultado}}
</ion-content>
</ion-pane>
</body>
</html>
12
Step by Step – app.js
// Database instance.
var db = null;
// Include dependency: ngCordova
var starter = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB({name: "my.db"});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS pessoas (id INTEGER PRIMARY KEY, firstname text, lastname text)");
});
})
starter.controller('DBController', function($scope, $cordovaSQLite) {
$scope.resultado = [];
$scope.mensagemFinal = "Iniciou Sistema";
$scope.insert = function(firstname, lastname) {
var query = "insert into pessoas (firstname, lastname) values (?,?)";
$cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) {
$scope.mensagemFinal = "FOI";
$scope.resultado.push({mensagem: "Insert Ok"});
console.log("Insert ID -> " + result.insertId);
}, function(error){
$scope.resultado.push({mensagem: "insert Fail"});
$scope.mensagemFinal = "Fail";
console.log(error);
});
}
13
Step by Step – app.js - continuation
$scope.select = function(lastname){
var query = "select firstname, lastname from pessoas where lastname = ?";
$cordovaSQLite.execute(db,query,[lastname]).then(function(result) {
if(result.rows.length > 0){
$scope.mensagemFinal = "ACHEI";
$scope.resultado = result.rows.item(0).firstname;
console.log("Achei " + result.rows.item(0).firstname + " " + result.rows.item(0).lastname);
} else {
$scope.mensagemFinal = "NAO ACHEI";
$scope.resultado = [];
console.log("Nao achei");
}
}, function(error){
console.log(error);
});
}
});
14
Step by Step
● Let's run with the command (you need to have an emulator or your physical phone
connected, in my case, I have Genymotion running):
ionic run android
15
TIP
● To see the Android log, go to the folder platform-tools from your sdk and run:
./adb logcat
● This is for Linux.
16
Creating a CRUD with Ionic – Part 2
Juliano Marcos Martins – juliano.jmm@gmail.com
http://jmmwrite.wordpress.com
17
Part 2
● We have created a code that insert and search for names, but, its hardcoded!
● Now we will create a FORM, to allow user type First and Last names and perform the
Insert and Search Operations with this data.
● We are not wondering about form validation for now, but, we will create a better UI at
least!
You can get the source code from this slides here →
https://github.com/julianommartins/ionicDataBase.git
18
Step by Step – index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DB Example</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane ng-controller="DBController">
<ion-header-bar class="bar-positive">
<h1 class="title">Pessoas</h1>
</ion-header-bar>
<ion-content>
<div class="list">
<label class="item item-input item-floating-label">
<span class="input-label">First Name</span>
<input type="text" placeholder="First Name" data-ng-model="fsName">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Last Name</span>
<input type="text" placeholder="Last Name" data-ng-model="lstName">
</label>
<button class="button button-balanced" ng-click="select(lstName)">Select</button>
<button class="button button-positive" ng-click="insert(fsName,lstName)">Insert</button>
<button class="button button-energized" ng-click="delete(lstName)">Delete</button>
<button class="button button-assertive" ng-click="update(fsName,lstName)">Update</button>
<label class="item item-input">
<input type="text" readonly value="{{resultado}}">
</label>
</div>
</ion-content>
<ion-footer-bar class="bar-positive">
<h1 class="title">Pessoas</h1>
</ion-footer-bar>
</ion-pane>
</body>
</html>
19
Step by Step – app.js
// Database instance.
var db = null;
// Include dependency: ngCordova
var starter = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB({name: "my.db"});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS pessoas (id INTEGER PRIMARY KEY, firstname text, lastname text)");
});
})
starter.controller('DBController', function($scope, $cordovaSQLite) {
$scope.resultado = "";
$scope.insert = function(firstname, lastname) {
var query = "insert into pessoas (firstname, lastname) values (?,?)";
$cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) {
//$scope.resultado.push({mensagem: "Insert Ok"});
$scope.resultado = "Insert Ok";
}, function(error){
$scope.resultado = "Insert FAIL";
});
}
20
Step by Step – app.js (continuation)
$scope.select = function(lastname){
var query = "select firstname, lastname from pessoas where lastname = ?";
$cordovaSQLite.execute(db,query,[lastname]).then(function(result) {
if(result.rows.length > 0){
$scope.resultado = result.rows.item(0).firstname + " found with this last name.";
} else {
$scope.resultado = "Not found";
}
}, function(error){
console.log(error);
});
}
});
21
Step by Step
● Let's run with the command (you need to have an emulator or your physical phone
connected, in my case, I have Genymotion running):
ionic run android
22
Part 3
● Now, lets implement the update and delete operations.
You can get the source code from this slides here →
https://github.com/julianommartins/ionicDataBase.git
23
Step by Step – app.js
$scope.delete = function(lastname) {
var query = "delete from pessoas where lastname = ?";
$cordovaSQLite.execute(db,query,[lastname]).then(function(result) {
$scope.resultado = "Delete Ok.";
}, function(error){
$scope.resultado = "Delete FAIL!";
});
}
$scope.update = function(firstname, lastname) {
var query = "update pessoas set firstname = ? where lastname = ?";
$cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) {
$scope.resultado = "Update OK.";
}, function(error){
$scope.resultado = "Update FAIL!";
});
}
Just add this functions to app.js
24
Part 4
● We have a Functional Crud, but now, we want a function to list all the people from DB!
● Also, we will remove the delete button and put it in the list, to let user swipe the user in
order to remove.
You can get the source code from this slides here →
https://github.com/julianommartins/ionicDataBase.git
25
Step by Step – index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DB Example</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane ng-controller="DBController">
<ion-header-bar class="bar-positive">
<h1 class="title">People List</h1>
</ion-header-bar>
<ion-content>
<label class="item item-input item-floating-label">
<span class="input-label">First Name</span>
<input type="text" placeholder="First Name" data-ng-model="fsName">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Last Name</span>
<input type="text" placeholder="Last Name" data-ng-model="lstName">
</label>
<button class="button button-balanced" ng-click="select(lstName)">Select</button>
<button class="button button-positive" ng-click="insert(fsName,lstName)">Insert</button>
<button class="button button-energized" ng-click="update(fsName,lstName)">Update</button>
<button class="button button-royal" ng-click="selectAll()">List</button>
<label class="item item-input">
<input type="text" readonly value="{{resultado}}">
</label>
<ion-list>
<ion-item ng-repeat="people in peopleList">
{{people.firstname}} {{people.lastname}}
<ion-option-button class="button-assertive icon ion-trash-a" ng-click='delete(people.lastname)'></ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-pane>
</body>
</html>
26
Step by Step – app.js
// Database instance.
var db = null;
// Include dependency: ngCordova
var starter = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB({name: "my.db"});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS pessoas (id INTEGER PRIMARY KEY, firstname text, lastname text)");
});
})
starter.controller('DBController', function($scope, $cordovaSQLite) {
$scope.resultado = "";
$scope.peopleList = [];
$scope.insert = function(firstname, lastname) {
$scope.peopleList = [];
var query = "insert into pessoas (firstname, lastname) values (?,?)";
$cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) {
//$scope.resultado.push({mensagem: "Insert Ok"});
$scope.resultado = "Insert OK.";
}, function(error){
$scope.resultado = "Insert FAIL!";
});
}
27
Step by Step – app.js - cont
$scope.select = function(lastname){
$scope.peopleList = [];
var query = "select firstname, lastname from pessoas where lastname = ?";
$cordovaSQLite.execute(db,query,[lastname]).then(function(result) {
if(result.rows.length > 0){
$scope.resultado = result.rows.item(0).firstname + " found with this last name.";
} else {
$scope.resultado = "Last Name Not Found!";
}
}, function(error){
console.log(error);
});
}
$scope.selectAll = function(){
$scope.peopleList = [];
var query = "select firstname, lastname from pessoas";
$cordovaSQLite.execute(db,query,[]).then(function(result) {
if(result.rows.length > 0){
for(var i = 0; i < result.rows.length; i++) {
$scope.peopleList.push({firstname: result.rows.item(i).firstname, lastname: result.rows.item(i).lastname});
}
$scope.resultado = result.rows.length + " rows found.";
} else {
$scope.resultado = "0 rows found!";
$scope.peopleList = [];
}
}, function(error){
console.log(error);
});
}
$scope.delete = function(lastname) {
$scope.peopleList = [];
var query = "delete from pessoas where lastname = ?";
$cordovaSQLite.execute(db,query,[lastname]).then(function(result) {
$scope.resultado = "Delete Ok.";
}, function(error){
$scope.resultado = "Delete FAIL!";
});
}
28
Step by Step – app.js - cont
$scope.update = function(firstname, lastname) {
$scope.peopleList = [];
var query = "update pessoas set firstname = ? where lastname = ?";
$cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) {
$scope.resultado = "Update OK.";
}, function(error){
$scope.resultado = "Update FAIL!";
});
}
// you can add a button to cleat he table!
$scope.deleteAll = function() {
$scope.peopleList = [];
var query = "delete from pessoas";
$cordovaSQLite.execute(db,query,[]).then(function(result) {
$scope.resultado = "Delete Ok.";
}, function(error){
$scope.resultado = "Delete FAIL!";
});
}
});
29
Step by Step
● Let's run with the command (you need to have an emulator or your physical phone
connected, in my case, I have Genymotion running):
ionic run android
30
To do!
● We have some things that we can make better:
● Need to validate data that user enter, like empty names.
● Clear the form after the submit
You can get the source code from this slides here →
https://github.com/julianommartins/ionicDataBase.git
31
Links
● Ionic JavaScript functionalities
http://ionicframework.com/docs/api/
● Ionic CSS
http://ionicframework.com/docs/components/
● Ionic Creator
http://creator.ionic.io/app/login
● Extensions for Cordova API
http://ngcordova.com/
32
All text and image content in this document is licensed under the Creative Commons Attribution-Share Alike 3.0 License
(unless otherwise specified). Adobe, Google, Apple, Apache, and other are registered trademarks. Their respective logos and
icons are subject to international copyright laws.
Thank you …
… for your dedication and patience!

More Related Content

ODP
Passo a Passo para criar uma aplicação Móvel Híbrida
ODP
Desenvolvimento Mobile Híbrido
PPT
PDF
Developers, Be a Bada$$ with WP-CLI
PPT
WordPress and Ajax
PDF
lecture5
PPT
Widget Summit 2008
PDF
Intro to WordPress Plugin Development
Passo a Passo para criar uma aplicação Móvel Híbrida
Desenvolvimento Mobile Híbrido
Developers, Be a Bada$$ with WP-CLI
WordPress and Ajax
lecture5
Widget Summit 2008
Intro to WordPress Plugin Development

What's hot (20)

PDF
The JavaFX Ecosystem
PDF
Introduction to Using PHP & MVC Frameworks
PDF
JavaFX Advanced
PDF
Building a Single Page Application using Ember.js ... for fun and profit
PPTX
Introduction to JQuery, ASP.NET MVC and Silverlight
PDF
High Performance JavaScript - WebDirections USA 2010
PPTX
JavaScript Performance (at SFJS)
PDF
Usability in the GeoWeb
PDF
JavaOne - The JavaFX Community and Ecosystem
PDF
Vue js and Vue Material
PDF
What The Flask? and how to use it with some Google APIs
PDF
Python Flask app deployed to OPenShift using Wercker CI
PDF
Behaviour Driven Development con Behat & Drupal
PDF
Build website in_django
PPT
Even Faster Web Sites at jQuery Conference '09
PDF
JavaFX in Action (devoxx'16)
PDF
WPDay Bologna 2013
PPTX
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
PPT
Jsf 2.0 in depth
PDF
Night Watch with QA
The JavaFX Ecosystem
Introduction to Using PHP & MVC Frameworks
JavaFX Advanced
Building a Single Page Application using Ember.js ... for fun and profit
Introduction to JQuery, ASP.NET MVC and Silverlight
High Performance JavaScript - WebDirections USA 2010
JavaScript Performance (at SFJS)
Usability in the GeoWeb
JavaOne - The JavaFX Community and Ecosystem
Vue js and Vue Material
What The Flask? and how to use it with some Google APIs
Python Flask app deployed to OPenShift using Wercker CI
Behaviour Driven Development con Behat & Drupal
Build website in_django
Even Faster Web Sites at jQuery Conference '09
JavaFX in Action (devoxx'16)
WPDay Bologna 2013
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Jsf 2.0 in depth
Night Watch with QA
Ad

Viewers also liked (20)

ODP
Desmistificando Tecnologias
ODP
Introdução a Big Data e Apache Solr
ODP
Criando um Web Service Restful com Jersey, Eclipse, JBoss, Tomcat, WebSphere
ODP
Software livre em minha carreira
PDF
IBM - The 7 Keys to Success - MoMoDar
PDF
Building Mobile Apps with Cordova , AngularJS and Ionic
PPT
A experiência do usuário na Web
PDF
php4android: desenvolva aplicações android em PHP
PDF
Offline apps Using Ionic Framework and PouchDB
PPT
Effective Communication Of Data Inspired by Stephen Few
PDF
Rethinking Mobile with Ionic
PDF
Crash Course in AngularJS + Ionic (Deep dive)
PPTX
Ionic 2 - Hybridapps auf Steroiden
PDF
Cordova, Angularjs & Ionic @ Codeaholics
PPTX
Ionic Framework - get up and running to build hybrid mobile apps
PDF
Workshop Ionic Framework - CC FE & UX
PDF
Art and Science of Dashboard Design
PPTX
Hybrid app in ionic framework overview
PDF
Hybrid Apps with Ionic Framework
PPTX
Building mobile app with Ionic Framework
Desmistificando Tecnologias
Introdução a Big Data e Apache Solr
Criando um Web Service Restful com Jersey, Eclipse, JBoss, Tomcat, WebSphere
Software livre em minha carreira
IBM - The 7 Keys to Success - MoMoDar
Building Mobile Apps with Cordova , AngularJS and Ionic
A experiência do usuário na Web
php4android: desenvolva aplicações android em PHP
Offline apps Using Ionic Framework and PouchDB
Effective Communication Of Data Inspired by Stephen Few
Rethinking Mobile with Ionic
Crash Course in AngularJS + Ionic (Deep dive)
Ionic 2 - Hybridapps auf Steroiden
Cordova, Angularjs & Ionic @ Codeaholics
Ionic Framework - get up and running to build hybrid mobile apps
Workshop Ionic Framework - CC FE & UX
Art and Science of Dashboard Design
Hybrid app in ionic framework overview
Hybrid Apps with Ionic Framework
Building mobile app with Ionic Framework
Ad

Similar to Desenvolvendo uma aplicação híbrida para Android e IOs utilizando Ionic, acessando SQLite (20)

KEY
Taking your Web App for a walk
KEY
SproutCore is Awesome - HTML5 Summer DevFest
PDF
Front End Development for Back End Java Developers - Jfokus 2020
PDF
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
PPTX
React django
PPTX
Mobile App Development: Primi passi con NativeScript e Angular 2
PDF
Ionic bbl le 19 février 2015
DOCX
Controller in AngularJS
PPTX
Mobile Apps with PhoneGap and jQuery Mobile
PDF
Using Renderless Components in Vue.js during your software development.
PDF
Ionic으로 모바일앱 만들기 #4
KEY
Javascript unit testing, yes we can e big
PDF
HotPush with Ionic 2 and CodePush
PPTX
AppForum 2014 Boost Hybrid App Performance
PPTX
lec 14-15 Jquery_All About J-query_.pptx
PDF
Meteor.js Workshop by Dopravo
KEY
Mobile optimization
PDF
Mini curso Android
PDF
Os Haase
PPTX
Apache Cordova In Action
Taking your Web App for a walk
SproutCore is Awesome - HTML5 Summer DevFest
Front End Development for Back End Java Developers - Jfokus 2020
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
React django
Mobile App Development: Primi passi con NativeScript e Angular 2
Ionic bbl le 19 février 2015
Controller in AngularJS
Mobile Apps with PhoneGap and jQuery Mobile
Using Renderless Components in Vue.js during your software development.
Ionic으로 모바일앱 만들기 #4
Javascript unit testing, yes we can e big
HotPush with Ionic 2 and CodePush
AppForum 2014 Boost Hybrid App Performance
lec 14-15 Jquery_All About J-query_.pptx
Meteor.js Workshop by Dopravo
Mobile optimization
Mini curso Android
Os Haase
Apache Cordova In Action

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Approach and Philosophy of On baking technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Encapsulation theory and applications.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Electronic commerce courselecture one. Pdf
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
The AUB Centre for AI in Media Proposal.docx
Approach and Philosophy of On baking technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Empathic Computing: Creating Shared Understanding
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
sap open course for s4hana steps from ECC to s4
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Reach Out and Touch Someone: Haptics and Empathic Computing
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Network Security Unit 5.pdf for BCA BBA.
Encapsulation theory and applications.pdf

Desenvolvendo uma aplicação híbrida para Android e IOs utilizando Ionic, acessando SQLite

  • 1. 1 Creating a CRUD with Ionic – Part 1 Juliano Marcos Martins – juliano.jmm@gmail.com http://jmmwrite.wordpress.com
  • 2. 2 SQLite Is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. https://www.sqlite.org/
  • 3. 3 Local Storage Can be used to store data, but don't Assume that it will Always Work In Your Hybrid App. // example localStorage.setItem('nome', 'Juliano'); var name = localStorage.getItem('nome'); console.log(name); IOs and Android can clean it in some situations.
  • 4. 4 Intro We will create an application to manage people from a table. Its recommended that you already have basic concepts about Ionic and Mobile Development before go ahead. For more intro material, check my blog: http://jmmwrite.wordpress.com/ You can get the source code from this slides here → https://github.com/julianommartins/ionicDataBase.git
  • 5. 5 Step by Step ● Create the project ionic start ionicDataBase blank
  • 6. 6 Step by Step ● Enter in the project folder and Add platform: ionic platform add android
  • 7. 7 Step by Step ● Add SQLite module (documentation: http://ngcordova.com/docs/plugins/sqlite/ ): cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storage.git
  • 8. 8 Step by Step ● Go to http://ngcordova.com/docs/install/ and get the JS lib (download the zip file) ● Extract it and get ng-cordova.min.js , put this file in the JS folder of your application * You can also use bower to get ng-cordova
  • 9. 9 Step by Step ● Open your index.html file and import ng-cordova there by adding the folowing line BEFORE cordova import: <script src="js/ng-cordova.min.js"></script>:
  • 10. 10 Step by Step ● Open your app.js file and inject ngCordova module: This will make module work!
  • 11. 11 Step by Step – index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DB Example</title> <link href="lib/ionic/css/ionic.css" rel="stylesheet"> <link href="css/style.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">Pessoas</h1> </ion-header-bar> <ion-content ng-controller="DBController"> <button class="button" ng-click="insert('Juliano','Martins')">Insert</button> <button class="button" ng-click="select('Martins')">Select</button> Resultado: {{mensagemFinal}} Resultado: {{resultado}} </ion-content> </ion-pane> </body> </html>
  • 12. 12 Step by Step – app.js // Database instance. var db = null; // Include dependency: ngCordova var starter = angular.module('starter', ['ionic', 'ngCordova']) .run(function($ionicPlatform, $cordovaSQLite) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } db = $cordovaSQLite.openDB({name: "my.db"}); $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS pessoas (id INTEGER PRIMARY KEY, firstname text, lastname text)"); }); }) starter.controller('DBController', function($scope, $cordovaSQLite) { $scope.resultado = []; $scope.mensagemFinal = "Iniciou Sistema"; $scope.insert = function(firstname, lastname) { var query = "insert into pessoas (firstname, lastname) values (?,?)"; $cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) { $scope.mensagemFinal = "FOI"; $scope.resultado.push({mensagem: "Insert Ok"}); console.log("Insert ID -> " + result.insertId); }, function(error){ $scope.resultado.push({mensagem: "insert Fail"}); $scope.mensagemFinal = "Fail"; console.log(error); }); }
  • 13. 13 Step by Step – app.js - continuation $scope.select = function(lastname){ var query = "select firstname, lastname from pessoas where lastname = ?"; $cordovaSQLite.execute(db,query,[lastname]).then(function(result) { if(result.rows.length > 0){ $scope.mensagemFinal = "ACHEI"; $scope.resultado = result.rows.item(0).firstname; console.log("Achei " + result.rows.item(0).firstname + " " + result.rows.item(0).lastname); } else { $scope.mensagemFinal = "NAO ACHEI"; $scope.resultado = []; console.log("Nao achei"); } }, function(error){ console.log(error); }); } });
  • 14. 14 Step by Step ● Let's run with the command (you need to have an emulator or your physical phone connected, in my case, I have Genymotion running): ionic run android
  • 15. 15 TIP ● To see the Android log, go to the folder platform-tools from your sdk and run: ./adb logcat ● This is for Linux.
  • 16. 16 Creating a CRUD with Ionic – Part 2 Juliano Marcos Martins – juliano.jmm@gmail.com http://jmmwrite.wordpress.com
  • 17. 17 Part 2 ● We have created a code that insert and search for names, but, its hardcoded! ● Now we will create a FORM, to allow user type First and Last names and perform the Insert and Search Operations with this data. ● We are not wondering about form validation for now, but, we will create a better UI at least! You can get the source code from this slides here → https://github.com/julianommartins/ionicDataBase.git
  • 18. 18 Step by Step – index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DB Example</title> <link href="lib/ionic/css/ionic.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <script src="lib/ionic/js/ionic.bundle.js"></script> <script src="js/ng-cordova.min.js"></script> <script src="cordova.js"></script> <script src="js/app.js"></script> </head> <body ng-app="starter"> <ion-pane ng-controller="DBController"> <ion-header-bar class="bar-positive"> <h1 class="title">Pessoas</h1> </ion-header-bar> <ion-content> <div class="list"> <label class="item item-input item-floating-label"> <span class="input-label">First Name</span> <input type="text" placeholder="First Name" data-ng-model="fsName"> </label> <label class="item item-input item-floating-label"> <span class="input-label">Last Name</span> <input type="text" placeholder="Last Name" data-ng-model="lstName"> </label> <button class="button button-balanced" ng-click="select(lstName)">Select</button> <button class="button button-positive" ng-click="insert(fsName,lstName)">Insert</button> <button class="button button-energized" ng-click="delete(lstName)">Delete</button> <button class="button button-assertive" ng-click="update(fsName,lstName)">Update</button> <label class="item item-input"> <input type="text" readonly value="{{resultado}}"> </label> </div> </ion-content> <ion-footer-bar class="bar-positive"> <h1 class="title">Pessoas</h1> </ion-footer-bar> </ion-pane> </body> </html>
  • 19. 19 Step by Step – app.js // Database instance. var db = null; // Include dependency: ngCordova var starter = angular.module('starter', ['ionic', 'ngCordova']) .run(function($ionicPlatform, $cordovaSQLite) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } db = $cordovaSQLite.openDB({name: "my.db"}); $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS pessoas (id INTEGER PRIMARY KEY, firstname text, lastname text)"); }); }) starter.controller('DBController', function($scope, $cordovaSQLite) { $scope.resultado = ""; $scope.insert = function(firstname, lastname) { var query = "insert into pessoas (firstname, lastname) values (?,?)"; $cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) { //$scope.resultado.push({mensagem: "Insert Ok"}); $scope.resultado = "Insert Ok"; }, function(error){ $scope.resultado = "Insert FAIL"; }); }
  • 20. 20 Step by Step – app.js (continuation) $scope.select = function(lastname){ var query = "select firstname, lastname from pessoas where lastname = ?"; $cordovaSQLite.execute(db,query,[lastname]).then(function(result) { if(result.rows.length > 0){ $scope.resultado = result.rows.item(0).firstname + " found with this last name."; } else { $scope.resultado = "Not found"; } }, function(error){ console.log(error); }); } });
  • 21. 21 Step by Step ● Let's run with the command (you need to have an emulator or your physical phone connected, in my case, I have Genymotion running): ionic run android
  • 22. 22 Part 3 ● Now, lets implement the update and delete operations. You can get the source code from this slides here → https://github.com/julianommartins/ionicDataBase.git
  • 23. 23 Step by Step – app.js $scope.delete = function(lastname) { var query = "delete from pessoas where lastname = ?"; $cordovaSQLite.execute(db,query,[lastname]).then(function(result) { $scope.resultado = "Delete Ok."; }, function(error){ $scope.resultado = "Delete FAIL!"; }); } $scope.update = function(firstname, lastname) { var query = "update pessoas set firstname = ? where lastname = ?"; $cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) { $scope.resultado = "Update OK."; }, function(error){ $scope.resultado = "Update FAIL!"; }); } Just add this functions to app.js
  • 24. 24 Part 4 ● We have a Functional Crud, but now, we want a function to list all the people from DB! ● Also, we will remove the delete button and put it in the list, to let user swipe the user in order to remove. You can get the source code from this slides here → https://github.com/julianommartins/ionicDataBase.git
  • 25. 25 Step by Step – index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DB Example</title> <link href="lib/ionic/css/ionic.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <script src="lib/ionic/js/ionic.bundle.js"></script> <script src="js/ng-cordova.min.js"></script> <script src="cordova.js"></script> <script src="js/app.js"></script> </head> <body ng-app="starter"> <ion-pane ng-controller="DBController"> <ion-header-bar class="bar-positive"> <h1 class="title">People List</h1> </ion-header-bar> <ion-content> <label class="item item-input item-floating-label"> <span class="input-label">First Name</span> <input type="text" placeholder="First Name" data-ng-model="fsName"> </label> <label class="item item-input item-floating-label"> <span class="input-label">Last Name</span> <input type="text" placeholder="Last Name" data-ng-model="lstName"> </label> <button class="button button-balanced" ng-click="select(lstName)">Select</button> <button class="button button-positive" ng-click="insert(fsName,lstName)">Insert</button> <button class="button button-energized" ng-click="update(fsName,lstName)">Update</button> <button class="button button-royal" ng-click="selectAll()">List</button> <label class="item item-input"> <input type="text" readonly value="{{resultado}}"> </label> <ion-list> <ion-item ng-repeat="people in peopleList"> {{people.firstname}} {{people.lastname}} <ion-option-button class="button-assertive icon ion-trash-a" ng-click='delete(people.lastname)'></ion-option-button> </ion-item> </ion-list> </ion-content> </ion-pane> </body> </html>
  • 26. 26 Step by Step – app.js // Database instance. var db = null; // Include dependency: ngCordova var starter = angular.module('starter', ['ionic', 'ngCordova']) .run(function($ionicPlatform, $cordovaSQLite) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } db = $cordovaSQLite.openDB({name: "my.db"}); $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS pessoas (id INTEGER PRIMARY KEY, firstname text, lastname text)"); }); }) starter.controller('DBController', function($scope, $cordovaSQLite) { $scope.resultado = ""; $scope.peopleList = []; $scope.insert = function(firstname, lastname) { $scope.peopleList = []; var query = "insert into pessoas (firstname, lastname) values (?,?)"; $cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) { //$scope.resultado.push({mensagem: "Insert Ok"}); $scope.resultado = "Insert OK."; }, function(error){ $scope.resultado = "Insert FAIL!"; }); }
  • 27. 27 Step by Step – app.js - cont $scope.select = function(lastname){ $scope.peopleList = []; var query = "select firstname, lastname from pessoas where lastname = ?"; $cordovaSQLite.execute(db,query,[lastname]).then(function(result) { if(result.rows.length > 0){ $scope.resultado = result.rows.item(0).firstname + " found with this last name."; } else { $scope.resultado = "Last Name Not Found!"; } }, function(error){ console.log(error); }); } $scope.selectAll = function(){ $scope.peopleList = []; var query = "select firstname, lastname from pessoas"; $cordovaSQLite.execute(db,query,[]).then(function(result) { if(result.rows.length > 0){ for(var i = 0; i < result.rows.length; i++) { $scope.peopleList.push({firstname: result.rows.item(i).firstname, lastname: result.rows.item(i).lastname}); } $scope.resultado = result.rows.length + " rows found."; } else { $scope.resultado = "0 rows found!"; $scope.peopleList = []; } }, function(error){ console.log(error); }); } $scope.delete = function(lastname) { $scope.peopleList = []; var query = "delete from pessoas where lastname = ?"; $cordovaSQLite.execute(db,query,[lastname]).then(function(result) { $scope.resultado = "Delete Ok."; }, function(error){ $scope.resultado = "Delete FAIL!"; }); }
  • 28. 28 Step by Step – app.js - cont $scope.update = function(firstname, lastname) { $scope.peopleList = []; var query = "update pessoas set firstname = ? where lastname = ?"; $cordovaSQLite.execute(db,query,[firstname,lastname]).then(function(result) { $scope.resultado = "Update OK."; }, function(error){ $scope.resultado = "Update FAIL!"; }); } // you can add a button to cleat he table! $scope.deleteAll = function() { $scope.peopleList = []; var query = "delete from pessoas"; $cordovaSQLite.execute(db,query,[]).then(function(result) { $scope.resultado = "Delete Ok."; }, function(error){ $scope.resultado = "Delete FAIL!"; }); } });
  • 29. 29 Step by Step ● Let's run with the command (you need to have an emulator or your physical phone connected, in my case, I have Genymotion running): ionic run android
  • 30. 30 To do! ● We have some things that we can make better: ● Need to validate data that user enter, like empty names. ● Clear the form after the submit You can get the source code from this slides here → https://github.com/julianommartins/ionicDataBase.git
  • 31. 31 Links ● Ionic JavaScript functionalities http://ionicframework.com/docs/api/ ● Ionic CSS http://ionicframework.com/docs/components/ ● Ionic Creator http://creator.ionic.io/app/login ● Extensions for Cordova API http://ngcordova.com/
  • 32. 32 All text and image content in this document is licensed under the Creative Commons Attribution-Share Alike 3.0 License (unless otherwise specified). Adobe, Google, Apple, Apache, and other are registered trademarks. Their respective logos and icons are subject to international copyright laws. Thank you … … for your dedication and patience!