My experience on my daily works... helping others ease each other

Showing posts with label Mobile World. Show all posts
Showing posts with label Mobile World. Show all posts

Wednesday, December 18, 2019

Ionic 4 + React + Capacitor - The right way of building mobile apps with these three

React is supported in Ionic starting from Ionic 4. And this is the issue if you started to develop ionic react apps by running command ionic start [appsname] --types=react.

I started with that command and it becomes issues of which it took me 3 days and still it won't work. Few issues found was:
1. You cannot build or compile into mobile apps with normal ionic cordova add android, etc commands. It will stated that it is a react apps and you need to use capacitor instead.
2. So you start to install capacitor and follow many steps. You will be succeed in building and compiling.
3. But, upon running the apps on emulator or your devices, you'll get blank screen. 

How to solve that? I've followed many steps including changing the default href in index.html, remove and add capacitor and rerun it. Yet it failed. 

How do I solve that? Here is the steps:

1. Remove everything

(base) % npm uninstall -g ionic    
up to date in 0.05s
(base) % npm uninstall -g capacitor
up to date in 0.045s
(base) % npm uninstall -g cordova  
up to date in 0.047s
(base) a% npm cache clean -f        
npm WARN using --force I sure hope you know what you are doing.

2. Update your NPM modules
(base) % npm i -g npm              

3. Install ionic with capacitor
(base) % npm install -g ionic capacitor

4. Create your apps
(base) % ionic start yourapps tabs --type=react

5. Run NPM install to install any modules required upon completed. For any additional modules, run npm install to ensure required modules is updated.
(base) % cd yourapps 
(base) % npm install

6. Run your apps to test it out
(base) % ionic serve

7. After doing your development, build it using npm run build or ionic build
(base) % npm run build

8. Next, build for your platform. Once build is completed, please ensure your www or public folder exist. Then add the required platform. In my case, I'm developing for android.
(base) % ionic cap add android

9. Open IDE. If succeed, proceed with opening the apps on XCode or Android Studio (depend on your chosen platform)
(base) % ionic cap run android

10. Once your IDE is opened, compile/build and run it on emulator or devices.

It shall do it.



Share:

Friday, August 31, 2018

Downloading and Formatting data for PDF output using Ionic, Angular, Cordova and TypeScript

It has been a while I did not focus and wrote anything on this blog and it is good to be back on track.

Lets kick start with writing PDF on your mobile apps. You may have data retrieve and your client require you to download the data as PDF. I've done that on Excel and it was way easy to do that.

Now lets start for PDF. It is pretty much easy too. We are going to use PDFMaker library.

If you follow the steps shows here, it shall be sufficient.

https://ionicacademy.com/create-pdf-files-ionic-pdfmake/

and you can read the entire library here

http://pdfmake.org/#/gettingstarted

You need to download and install three libraries for it to work
# Install Cordova Plugins
1. ionic cordova plugin add cordova-plugin-file-opener2
2. ionic cordova plugin add cordova-plugin-file

#Install NPM packages
3. npm install pdfmake @ionic-native/file-opener @ionic-native/file
Once complete, declare it in your apps.module.ts. The link above shall guide you with the sample.

The link above shows how it was done in a single page.  I, on the other hand, create a service provider to ease me in sharing the service between the apps. Below is the snapshot of my code... and Yup, I'm using Promise to ensure I can control the outcome and catch any error.

#the import
import { Platform } from 'ionic-angular';
//import { Http } from '@angular/http';
import { Injectable, Component } from '@angular/core';

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';

#the control
createPdf( isMin: boolean ): Promise<any>{
return new Promise ((resolve,reject) => {
if( isMin ){
this.createPdfMin()
.then((data) => {
return resolve( data );
})
.catch( (error) => {
return reject( error );
})
} else {
this.createPdfMax()
.then((data) => {
return resolve( data );
})
.catch( (error) => {
return reject( error );
})
}
})
} //end createPdf

#partial code to create pdf
createPdfMin(): Promise<any>{
//let docDefinition = null;

return new Promise((resolve) => {
let docDefinition = {
// a string or { width: number, height: number }
pageSize: 'A4',

// by default we use portrait, you can change it to landscape if you wish
pageOrientation: 'potrait',

// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [ 10, 30, 10, 30 ],

content: [
{ text: 'The Header', style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
//SPA Section
{ text: 'Sub Header', style: 'subheader' },

{ text: 'Sub Sub Header', style: 'subheader2' },
{
columns: [
{
text: 'Intial data'
},
{
width: '*',
text: theValue.toLocaleString('en-US', {
style: 'currency',
currency: 'MYR',
})
}
],
// optional space between columns
columnGap: 10
},
{ text: '---------------------------------------------------', style: 'subheader2' },
],
styles: {
header: {
fontSize: 18,
bold: true,
},
subheader: {
fontSize: 14,
bold: true,
margin: [0, 15, 0, 0]
},
subheader2: {
fontSize: 12,
bold: true,
margin: [0, 15, 0, 0]
},
story: {
italic: true,
alignment: 'center',
width: '50%',
}
}
}

this.pdfObj = pdfMake.createPdf(docDefinition);

return resolve( this.pdfObj );
});
} //end createPdfMin

#code to download the pdf
downloadPdf(pdfObj, type:string):Promise<any>{
console.log('fileCreator.downloadPdf()');
return new Promise((resolve) => {
if (this.plt.is('cordova')) {
pdfObj.getBuffer((buffer) => {
var blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.dataDirectory, 'file_' + type + '.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
this.fileOpener.open(this.file.dataDirectory + 'file_' + type + '.pdf', 'application/pdf');
})
});
} else {
// On a browser simply use download!
this.pdfObj.download();
}
return resolve("success");
})
} //end function downloadPdf

#how it is called from other page or file
this.fileCreatorProvider.createPdf(true)
.then((data) =>{
//download the file for min
this.fileCreatorProvider.downloadPdf(data,'type')
.then((data) => {
if ( data === 'success'){
this.presentAlert('Download Complete','Successfully download the file','success');
} else {
this.presentAlert('Download Error','Fail to download the file','error');
}
})
.catch((error) => {
this.presentAlert('Download Error','Fail to download the file. Catch ' + error,'error');
})
})
.catch((error) => {
this.presentAlert('Download Error','Fail to download the file. Catch ' + error,'error');
})


and you shall be ready.

By the way, it is just snapshot. It shall give you brief idea on how to do that.

Happy Coding!!!


Share:

Sunday, February 18, 2018

Save list as CSV in ionic (PWA)

Read/Write file into devices

Installation (https://ionicframework.com/docs/native/file/)

Install the Cordova and Ionic Native plugins:
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save @ionic-native/file
Add this plugin to your app's module

There are few ways you can use to download the file, but I'm using the easiest way, that is implementing the download which I'm not pretty sure if it runs ok on Android and iOS.
I'm not writing directly into the device storage as there are many things to consider such as storage area, security, etc.

Few references:

  1. http://ngcordova.com/docs/plugins/file/
  2. https://www.npmjs.com/package/cordova-plugin-file
  3. https://github.com/apache/cordova-plugin-file
  4. https://github.com/jiahao1553/demo-ionic2-save-csv/blob/master/src/pages/home/home.ts
Share:

Wednesday, December 27, 2017

Set the display to center using Ionic

If you are developing apps focusing only on mobile, you may not be facing display issue as the user won't be able to see gaps or alignment problem. However, if you are developing apps that required to run on multiple platforms including web and mobile, aligning your display may cause a problem.

You will spend lots of time to configure your .css (or .scss) and when you thought you solved the problem on mobile, it shows differently on web.

I too faced such difficulties and finally found a way to solve it. I'm using ion-card and ion-list together.

here are snapshot of the code
<ion-card-content style="justify-content: center; margin-left: 0px; margin-right:
0px;background-color: #000000;">
<ion-card-title style="color: #fcfa87">
Center content <br> Working together
</ion-card-title>
<ion-list no-lines style="justify-content: center; margin-left: 0px;
margin-right: 0px; background-color: #030303;">
<ion-item style="background-color: #f1f7d6;">
<ion-label floating class="item item-input">Username</ion-label>
<ion-input type="text" name="username" class="input-label"></ion-input>
</ion-item>

and of course you need to configure your .scss too

snapshot of the code
.displayed {
display: block;
margin-left: auto;
margin-right: auto;
}
.card{
width:100%;
margin: auto;
}

the first (.displayed) shall be call by your ion-content tags and the .card is automatically set the card to be 100% width depending on your screen size

and it shall be displaying nicely on any screen as shown below
On web browser

On iPhone 7
For complete source code, you can download from my github.

All the best coding :)

Share:

Thursday, March 2, 2017

Get start with ionic framework

When I first developed apps using ionic, not many resources over the net will provide good explanation on it. I've found one and it is very easy to understand.

Here is the structure of ionic framework after it successfully execute ionic start command; for example 

ionic start myfirst blank --v2

>> ionic start [your_apps_name] [template] [ionic_framework_version]

the command will create a new folder (myfirst) and construct the following structures

├── hooks // custom cordova hooks to execute on specific commands 
├── platforms // iOS/Android specific builds will reside here 
├── plugins // where your cordova/ionic plugins will be installed 
├── resources // icon and splash screen 
├── scss // scss code, which will output to www/css/
 |── www // application - JS code and libs, CSS, images, etc. 
      |---------css //customs styles 
      |---------img //app images 
      |---------js //angular app and custom JS 
      |---------lib //third party libraries 
      |---------index.html //app master page 
├── bower.json // bower dependencies 
├── config.xml // cordova configuration 
├── gulpfile.js // gulp tasks 
├── ionic.project // ionic configuration 
├── package.json // node dependencies


Following are current potential templates that you can use:
  • tabs : a simple 3 tab layout
  • sidemenua layout with a swipable menu on the side
  • blanka bare starter with a single page
  • superstarter project with over 14 ready to use page designs
  • tutoriala guided starter project

Once it is completed, you will get to see the following message appear:
Downloading: https://github.com/driftyco/ionic2-app-base/archive/master.zip
Downloading: https://github.com/driftyco/ionic2-starter-                   sidemenu/archive/master.zip                                                
Installing npm packages (may take a minute or two)...                      
-                                                                          
♬ ♫ ♬ ♫  Your Ionic app is ready to go! ♬ ♫ ♬ ♫                          
                                                                           
Some helpful tips:                                                         
                                                                           
Run your app in the browser (great for initial development):               
  ionic serve                                                              
                                                                           
Run on a device or simulator:                                              
  ionic run ios[android,browser]                                           
                                                                           
Share your app with testers, and test on device easily with the Ionic View companion app:                                                             
  http://view.ionic.io                                                     

Yeah... now you test your apps. Just run ionic serve to view on your browser. It will pop-up your browser and automatically navigate to http://localhost:8100 ... else, you can open your browser and go to the address.

If you want to view in mobile, you may use mobile emulator or deploy on your mobile. Before that, do install mobile platform package first. To do that, run the following command:

                                                                       
ionic platform add ios  // to add ios platform into the package      
                                                                     
ionic platform add android //to add android platform into the package  
                                                                       

Finally, you are ready to run (on emulator or actual device).


                                                                           
ionic run android --prod --release //to run on emulator as production mode 
                                                                           
ionic build android --prod --release //to build as package for installation
                                                                           

For ios, it will require more steps and you can follow it https://ionicframework.com/docs/v2/intro/deploying/.

Lets dance... :)
Share:

Tuesday, July 7, 2015

Be a Data Scientist

Leverage your degree to solve real-world problems.

The Data Science Incubator is an intensive eight-week data science program that prepares top science and engineering graduates to work as data scientists and quants in the private secroe. We then help you find jobs at some of the world's top companies. the program is free for this Data Scientist.

Join us in Kuala Lumpur. Apply today!

Registration is now open till 27th July 2015

  1. Hurry now! Deadline is approaching. We are growing rapidly and admitting more candidates than ever. Afew notes:
  2. Interested in applying? Please apply via http://www.ibigmaxe.com[ibigmaxe.com]
  3. Taken Entrance Exam? you will receive an email notification after you have successfully registered.
  4. Qualified yet? An email your way to nofity if you have been selected.
  5. Want to start preparing early? 12 Days Pre-Program for you via email to the qualified candidates.
  6. Not qualified? Want to apply for a later session? Sit tight: we will send emails about the future sessions to your email address.
  7. Know someone else who would make a great Data Scientist? Encourage them to apply at http://www.ibigmaxe.com[ibigmaxe.com]

Class starting on 17 August 2015!
http://www.ibigmaxe.com/
Share:

Sunday, December 28, 2014

merger failed : uses-sdk:minSdkVersion 16 cannot be different than version L declared in library [project_path]\AndroidManifest.xml

After so long design and draw system/solution/software architecture, my programming skill seem rusted. Thought of venturing into programming again as part-time, I started to look into java (still love Netbeans) and Android programming (used Android Studio v1.0.2) for mobile development....And it throw the first challenge to me... can't compiled a sample program. HUH!

First time loading.. got this error:
merger failed : uses-sdk:minSdkVersion 16 cannot be different than version L declared in library [project_path]\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\21.0.0-rc1\AndroidManifest.xml

Google the issues and found many link.. mostly at StackOverflow ... but it does not helpful at all. After a while googling it, found a solutions that solve my 2 days problem. A simple solutions; change all sdkVersion to "android-L" and compiled it again... and it works... yeeehaaa... here is how it looks like.

before change in file build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.app.masteramuk.myfirstapp"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.+'

after change in file build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion "android-L"
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.app.masteramuk.myfirstapp"
        minSdkVersion "android-L"
        targetSdkVersion "android-L"
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])


notes:
  • just change the file build.gradle
  • only apply to code using Android SDK or Android Studio
  • only apply to code that requires to be compatible with lower SDK @ lower Android
Thanks to simple but workable solutions from reddit
Share:

Monday, January 7, 2013

10 Steps to Smartphone Security for Android

With more and more Malaysians are adopting smartphones, we at CI feel obliged to share some tips pertaining to smartphone security with the users. We thought we should start with the fastest growing smartphone OS out there; i.e. Android. Please feel free to email us your thoughts.

Smartphones continue to grow in popularity and are now as powerful and functional as many computers. It is important to protect your smartphone just like you protect your computer as mobile cyber-security threats are growing. Mobile security tips can help you reduce the risk of exposure to mobile security threats.

  • Set PINs and passwords. To prevent unauthorized access to your phone, set a password or Personal Identification Number (PIN) on your phone’s home screen as a first line of defense in case your phone is lost or stolen. When possible, use a different password for each of your important log-ins (email, banking, personal sites, etc.). You should configure your phone to automatically lock after five minutes or less when your phone is idle, as well as use the SIM password capability available on most smartphones.
  • Do not modify your smartphone’s security settings. Do not alter security settings for convenience. Tampering with your phone’s factory settings, jailbreaking, or rooting your phone undermines the built-in security features offered by your wireless service and smartphone, while making it more susceptible to an attack.
  • Backup and secure your data. You should backup all of the data stored on your phone – such as your contacts, documents, and photos. These files can be stored on your computer, on a removal storage card, or in the cloud. This will allow you to conveniently restore the information to your phone should it be lost, stolen, or otherwise erased.
  • Only install apps from trusted sources. Before downloading an app, conduct research to ensure the app is legitimate. Checking the legitimacy of an app may include such thing as: checking reviews, confirming the legitimacy of the app store, and comparing the app sponsor’s official website with the app store link to confirm consistency. Many apps from untrusted sources contain malware that once installed can steal information, install viruses, and cause harm to your phone’s contents. There are also apps that warn you if any security risks exist on your phone.
  • Understand app permissions before accepting them. You should be cautious about granting applications access to personal information on your phone or otherwise letting the application have access to perform functions on your phone. Make sure to also check the privacy settings for each app before installing.
  • Install security apps that enable remote location and wiping. An important security feature widely available on smartphones, either by default or as an app, is the ability to remotely locate and erase all of the data stored on your phone, even if the phone’s GPS is off. In the case that you misplace your phone, some applications can activate a loud alarm, even if your phone is on silent. These apps can also help you locate and recover your phone when lost.
  • Accept updates and patches to your smartphone’s software. You should keep your phone’s operating system software up-to-date by enabling automatic updates or accepting updates when prompted from your service provider, operating system provider, device manufacturer, or application provider. By keeping your operating system current, you reduce the risk of exposure to cyber threats.
  • Be smart on open Wi-Fi networks. When you access a Wi-Fi network that is open to the public, your phone can be an easy target of cyber criminals. You should limit your use of public hotspots and instead use protected Wi-Fi from a network operator you trust or mobile wireless connection to reduce your risk of exposure, especially when accessing personal or sensitive information. Always be aware when clicking web links and be particularly cautious if you are asked to enter account or log-in information.
  • Wipe data on your old phone before you donate, resell or recycle it. Your smartphone contains personal data you want to keep private when you dispose your old phone. To protect your privacy, completely erase data off of your phone and reset the phone to its initial factory settings. Now having wiped your old device, you are free to donate, resell, recycle or otherwise properly dispose of your phone.
  • Report a stolen smartphone. The major wireless service providers, in coordination with the FCC, have established a stolen phone database. If your phone is stolen, you should report the theft to your local law enforcement authorities and then register the stolen phone with your wireless provider. This will provide notice to all the major wireless service providers that the phone has been stolen and will allow for remote “bricking” of the phone so that it cannot be activated on any wireless network without your permission.
Note: The above tips were adopted from Federal Communications Commission of the US website.

Information on how to implement these tips on your Android device can be found atsupport.google.com/googleplay.

CI Infosec News & Tips for You 
 Bringing you the latest happenings in information security and some essential tips to protect yourself and your information.
Share:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Labels

Blog Archive

Blogger templates