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

8,822 views

Published on

Neste conjunto de slides, demonstro a criação de uma aplicação híbrida para Android e IOs (Iphone) utilizando Ionic, Cordova e acessando SQLite, que irá executar as oprações básicas: incluir, listar, excluir e alterar dados.
Código fonte disponível em https://github.com/julianommartins/ionicDataBase

Published in: Technology
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
8,822
On SlideShare
0
From Embeds
0
Number of Embeds
6,404
Actions
Shares
0
Downloads
160
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

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

  1. 1. 1 Creating a CRUD with Ionic – Part 1 Juliano Marcos Martins – juliano.jmm@gmail.com http://jmmwrite.wordpress.com
  2. 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. 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. 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. 5 Step by Step ● Create the project ionic start ionicDataBase blank
  6. 6. 6 Step by Step ● Enter in the project folder and Add platform: ionic platform add android
  7. 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. 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. 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. 10 Step by Step ● Open your app.js file and inject ngCordova module: This will make module work!
  11. 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. 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. 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. 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. 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. 16 Creating a CRUD with Ionic – Part 2 Juliano Marcos Martins – juliano.jmm@gmail.com http://jmmwrite.wordpress.com
  17. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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!

×