Ionic App: SQLite doesn't work in emulator - android

Hello I am trying to follow a tutorial about implementing sqlite in an ionic app: https://www.youtube.com/watch?v=E6h8PFHMLIU
I did everything as proposed in the turoial but still when I run the application in the android emulator (ionic cordova build android; ionic cordova run android) it does not display the data from the database as in the video. What am I doing wrong? Below you can see the code
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { IonicStorageModule } from '#ionic/storage';
import { HttpModule } from '#angular/http';
import { DatabaseProvider } from '../providers/database/database';
import { SQLitePorter } from '#ionic-native/sqlite-porter';
import { SQLite } from '#ionic-native/sqlite';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
HttpModule,
IonicStorageModule.forRoot(),
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
DatabaseProvider,
SQLitePorter,
SQLite
]
})
export class AppModule {}
database.ts
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { SQLitePorter } from '#ionic-native/sqlite-porter';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { BehaviorSubject } from 'rxjs/Rx';
import { Storage } from '#ionic/storage';
#Injectable()
export class DatabaseProvider {
database: SQLiteObject;
private databaseReady: BehaviorSubject<boolean>;
constructor(public sqlitePorter: SQLitePorter, private storage: Storage, private sqlite: SQLite, private platform: Platform, private http: Http) {
this.databaseReady = new BehaviorSubject(false);
this.platform.ready().then(() => {
this.sqlite.create({
name: 'developers.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.database = db;
this.storage.get('database_filled').then(val => {
if (val) {
this.databaseReady.next(true);
} else {
this.fillDatabase();
}
});
});
});
}
fillDatabase() {
this.http.get('assets/dummyDump.sql')
.map(res => res.text())
.subscribe(sql => {
this.sqlitePorter.importSqlToDb(this.database, sql)
.then(data => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
})
.catch(e => console.error(e));
});
}
addDeveloper(name, skill, years) {
let data = [name, skill, years]
return this.database.executeSql("INSERT INTO developer (name, skill, yearsOfExperience) VALUES (?, ?, ?)", data).then(data => {
return data;
}, err => {
console.log('Error: ', err);
return err;
});
}
getAllDevelopers() {
return this.database.executeSql("SELECT * FROM developer", []).then((data) => {
let developers = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
developers.push({ name: data.rows.item(i).name, skill: data.rows.item(i).skill, yearsOfExperience: data.rows.item(i).yearsOfExperience });
}
}
return developers;
}, err => {
console.log('Error: ', err);
return [];
});
}
getDatabaseState() {
return this.databaseReady.asObservable();
}
}
home.ts
import { DatabaseProvider } from './../../providers/database/database';
import { Component } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
developer = {};
developers = [];
constructor(public navCtrl: NavController, private databaseprovider: DatabaseProvider, private platform: Platform) {
this.databaseprovider.getDatabaseState().subscribe(rdy => {
if (rdy) {
this.loadDeveloperData();
}
})
}
loadDeveloperData() {
this.databaseprovider.getAllDevelopers().then(data => {
this.developers = data;
})
}
addDeveloper() {
this.databaseprovider.addDeveloper(this.developer['name'], this.developer['skill'], parseInt(this.developer['yearsOfExperience']))
.then(data => {
this.loadDeveloperData();
});
this.developer = {};
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Developer Data
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-item>
<ion-label stacked>What's your name?</ion-label>
<ion-input [(ngModel)]="developer.name" placeholder="Developer Name"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>What's your special skill?</ion-label>
<ion-input [(ngModel)]="developer.skill" placeholder="Special Skill"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>How long have you been working?</ion-label>
<ion-input [(ngModel)]="developer.yearsOfExperience" placeholder="Years of experience"></ion-input>
</ion-item>
<button ion-button full (click)="addDeveloper()">Add Developer Info</button>
<ion-list>
<ion-item *ngFor="let dev of developers">
<h2>{{ dev.name }}</h2>
<p>{{ dev.yearsOfExperience }} years of {{ dev.skill }} Experience!</p>
</ion-item>
</ion-list>
</ion-content>

Related

Ionic App.component.html Session not showing

I want to show session in html called {{nama_cust}} at app.component.html, but it didn't show anything / blank, is something wrong with the code? Or app.component can't process session?
Here's my code.
app.component.html
<ion-app>
<ion-split-pane>
<ion-menu type="overlay" id="menu-avatar">
<ion-header>
<ion-toolbar>
<ion-title>{{nama_cust}}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<div #header>
<ion-row style="align-items:center;">
<ion-col col-6>
<img class="user-avatar" (click)="asd()" src="assets/ava/dum.jpg"/>
</ion-col>
<ion-col col-3>
<h4 id="tes"> {{nama_cust}} </h4>
</ion-col>
</ion-row>
</div>
app.component.ts
import { Component, NgModule, OnInit } from '#angular/core';
import { Platform, ToastController, IonicModule } from '#ionic/angular';
import { Router } from '#angular/router';
import { Storage, IonicStorageModule } from '#ionic/storage';
import { PostProvider } from 'src/providers/post-provider';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
public appPages = [
{
title: 'Home',
url: '/home',
icon: 'home'
},
{
title: 'List',
url: '/list',
icon: 'list'
}
];
anggota: any;
nama_cust: string;
constructor(
private router: Router,
private postPvdr: PostProvider,
private storage: Storage,
public toastCtrl: ToastController,
private sanitizer: DomSanitizer
) {}
ngOnInit() {
}
ionViewWillEnter() {
this.storage.get('session_storage').then((res) => {
this.anggota = res;
this.nama_cust = sessionStorage.getItem(this.nama_cust);
console.log(res);
});
}
}
console.log(res) is showing the content of the session, but when I call the session in the html as {{nama_cust}} it shows nothing. Here's how it looks, there should be a text above the cat picture and next to it, but it doesn't show anything.
You're calling getItem() on sessionStorage with an undefined key:
this.nama_cust = sessionStorage.getItem(this.nama_cust);
So there's nothing to retrieve that's why you're not seeing anything.
nama_cust has been initialized, but doesn't have a value assigned.
You need to get it from the response:
this.storage.get('session_storage').then((res) => {
this.anggota = res;
this.nama_cust = res.result.nama_cust;
console.log(res);
});

how to launch camera in an ionic app

I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}

Ionic Android Issue: scan function not working

I am new to angularjs and ionic cordova. I am following the code given in this video lecture on ionic cordova BLE plugin module. I am trying to make this work using ionic 3 and have installed ionic cordova plugin for BLE.
https://www.youtube.com/watch?v=chfXawb_eVY&t=1898s
I have followed the exact instruction. Here's are my code files:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { BLE } from '#ionic-native/ble';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
BLE
]
}) export class AppModule {}
home.ts
import { Component, NgZone } from '#angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '#ionic-native/ble';
import { ToastController } from 'ionic-angular';
import { setTimeout } from 'core-js/library/web/timers';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
devices: any[] = [];
statusMessage:string;
constructor(public navCtrl: NavController,
public toastCtrl: ToastController,
private ble: BLE,
private ngZone: NgZone) {
}
scan(){
this.setStatus('Scanning for bluetooth LE devices');
this.devices = [];
this.ble.scan([], 2).subscribe(
device=>this.onDeviceDiscovered(device),
error=>this.scanError(error)
);
setTimeout(this.statusMessage.bind(this),5000,'Scan Complete');
}
onDeviceDiscovered(device){
console.log('Scanning');
console.log('Discovered ' + JSON.stringify(device,null,2));
this.ngZone.run(()=>{
this.devices.push(device);
});
}
scanError(error) {
console.log('Check your bluetooth connection');
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
BLE Scanner
</ion-title>
<ion-buttons end>
<button ion-button (click)="scan()">
Scan
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item *ngFor="let device of devices">
<h2>{{ device.name || 'Unnamed' }}</h2>
<p>{{ device.id }}</p>
<p>RSSI:{{ device.rssi }}></p>
</button>
</ion-list>
</ion-content>
The function scanError is not written in the video, I have wrote it.
This is the webview screenshot
this.setStatus function is not defined. However, in the video, the function has not been declared. I tried by declaring
setStatus:any
but the function still displayed the same message. Also, I am not able to get any messages in the console even if I remove the setStatus function.
I have included NgZone component at the beginning.
Is there any way to get this resolved or am I missing something?
You need to write a setStatus function in your code.
setStatus(message) {
console.log(message);
this.ngZone.run(() => {
this.statusMessage = message;
});
}
The code on the slides is abbreviated. The source code for the examples in the presentation is available on github https://github.com/don/ionic-ble-examples

ionic2 Streaming Media is not working

I'm using the streaming media plugin in my ionic2 application.
this is my code:
let option:StreamingAudioOptions = {
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) }
}
this.streamingMedia.playAudio('http://sounddible.com/grab.php?id=2196&type=mp3',option);
the errorCallback return "Class not found"
Any help for explain the reason of this log
Thanks.
try below code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private streamingMedia: StreamingMedia) {}
startAudio(){
let options: StreamingAudioOptions = {
successCallback: () => { console.log('Video played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) },
initFullscreen:false,
};
this.streamingMedia.playAudio('YOUR_URL', options);
}

Can't resolve all parameters for Push: (?, ?)

I'm new at Ionic2.I am developing a test application on ionic 2,There are many features in it(SMS,Call Number,Chart,MySql,Push ...)I just followed the steps for push notification.push notification link.But I get an error and I do not get the cause.Where do i make mistakes
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import {
Push,
PushToken
} from '#ionic/cloud-angular';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html',
providers: [Push]
})
export class MyApp {
rootPage:any = HomePage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen:
SplashScreen,public push:Push) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
});
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import {CallNumber} from '#ionic-native/call-number';
import { SMS } from '#ionic-native/sms';
import {ChartPage} from '../pages/chart/chart';
import {CallNumberPage} from '../pages/call-number/call-number';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { Toast } from '#ionic-native/toast';
import { HttpModule } from '#angular/http';
import {CloudSettings,CloudModule} from '#ionic/cloud-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import {CanvasPage} from '../pages/canvas/canvas';
import {SqlitePage} from '../pages/sqlite/sqlite';
import {MysqlPage} from '../pages/mysql/mysql';
import {ServiceProvider} from '../providers/datamember';
import {ListPage} from '../pages/list/list';
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'xxxxxxx',
},
'push': {
'sender_id': 'xxxxxxxxx',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#343434'
}
}
}
};
#NgModule({
declarations: [
MyApp,
HomePage,
ChartPage,
CallNumberPage,
CanvasPage,
SqlitePage,
MysqlPage,
ListPage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
ChartPage,
CallNumberPage,
CanvasPage,
SqlitePage,
MysqlPage,
ListPage
],
providers: [
StatusBar,
SplashScreen,
CallNumber,
SMS,
SQLite,
Toast,
ServiceProvider,
HttpModule,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
You need to have the cloud client setup to use Push . Check here
Add CloudModule to imports.
imports: [
BrowserModule,
HttpModule,
CloudModule.forRoot(cloudSettings), //here
IonicModule.forRoot(MyApp)
],

Categories

Resources