Saturday, September 28, 2013

Adding Plugins to Cordova iOS Project.


In one of the previous blogpost, we have created a Cordova iOS project, configured it on XCode and launched the app on the simulator. In this blogpost, we will add plugins to the iOS project.

Similar to Android project, we will add one core plugin which was a part of Cordova core API's till previous releases. And then we will continue to add one third party plugin.

First we need to create a Cordova project following the steps from the previous blog.



Device plugin


We will add Device plugin which was a part of Cordova core API's in the previous versions of Cordova.

The device plugin is available the following git repository.

https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

So run the following command to add the device plugin to the project created.

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git





Now that we have added the device plugin to the project, let us use the Device API in our project.

We will make some simple changes to test if the functionality related to Device API is working or not.

Modify your onDeviceReady function in index.js file of your <Project Name>\www\js directory to display the information related to device. 

The modifications(in red) are given below.

 onDeviceReady: function() {
        app.receivedEvent('deviceready');
 var element = document.getElementById('deviceProperties');
        element.innerHTML = 'Device Name: '     + device.name     + '<br />' +
                            'Device Cordova: '  + device.cordova  + '<br />' +
                            'Device Platform: ' + device.platform + '<br />' +
                            'Device UUID: '     + device.uuid     + '<br />' +
                            'Device Model: '    + device.model    + '<br />' +
                            'Device Version: '  + device.version  + '<br />';
    },

Now we will make modifications to index.html file in <Project Name>\www\ folder to display the device information retrieved from the above functions.

<div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
<p id="deviceProperties">Loading device properties...</p>
            </div>
<div>

Now we will add ios platform by running the below command

cordova platform add ios



Now import this project into XCode, launch the emulator and see the device related changes in the app.





It displays the information like cordova version, device platform, device model and the os on device correctly. Since Device name is depreciated don't worry about the undefined displayed. 

So we are able to add the core Device API to the Cordova 3 project , make changes to the html and javascript files to use the functions from Device API and create an iOS project, build and launch the iOS project using Cordova Device API.

Now we will add another third party Cordova plugin to the project we created.

Barcode scanner plugin



The Barcode scanner plugin is available the following link.


Run the below command to add the Barcode scanner to the project.

cordova plugin add https://github.com/wildabeast/BarcodeScanner




Now we will use the functionality from this barcode scanner in project we created.

Add a button to trigger the bar code scanner in index.html file of <Project Name>\www\ folder.

The lines of code that needs to be added are indicated  in red. The other lines are already there, either from the project creation or from the previous modifications.

 <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
<p id="deviceProperties">Loading device properties...</p>
            </div>
<div>
     <button id="btnStart">Start Barcode scanner</button>
</div>



Add the reference of button to the index.js file at <Project Name>\www\js directory.

The lines of code that needs to be added are indicated in red. The other lines are already there either from the project creation or from the previous modifications.

 onDeviceReady: function() {
        app.receivedEvent('deviceready');
 var element = document.getElementById('deviceProperties');
        element.innerHTML = 'Device Name: '     + device.name     + '<br />' +
                            'Device Cordova: '  + device.cordova  + '<br />' +
                            'Device Platform: ' + device.platform + '<br />' +
                            'Device UUID: '     + device.uuid     + '<br />' +
                            'Device Model: '    + device.model    + '<br />' +
                            'Device Version: '  + device.version  + '<br />';
 var btnStart = document.getElementById('btnStart');

    },

Add this code at the end of the file.

 btnStart.addEventListener('click', function(){
            cordova.plugins.barcodeScanner.scan(
      function (result) {
          alert("We got a bar code\n" +
                "Result: " + result.text + "\n" +
                "Format: " + result.format + "\n" +
                "Cancelled: " + result.cancelled);
      }, 
      function (error) {
          alert("Scanning failed: " + error);
      }
   );
        });

We have added the bar code scanner plugin, added a button to trigger the barcode scanning and code to trigger the barcode scanner plugin up on clicking the button.

Now we need to remove the existing iOS platform , add the iOS  Platform again and then build the iOS  project and the application again and launch it from XCode.



And the application will install the application on the emulator and launch the application in the emulator.


We can see a button at the bottom of  screen, which is created by us to trigger Barcode scanner functionality.
Click on button and if you are running on a simulator like me, you will see a failure message like the below. Else 
 the barcode scanner should be at work.



Sunday, September 22, 2013

Adding plugins to your Cordova Android project.

In one of the previous blogposts , we have seen how to create a Cordova Android project and also configured it on eclipse and launched it in an emulator.

In this blog post we will add one core plugin which is a part of core Cordova API in the previous versions and one third party plugin.

First we need start by creating a new Cordova project from the steps in the previous blog post.

Device plugin


We will add Device plugin which was a part of Cordova core API's in the previous versions of Cordova.

The device plugin is available the following git repository.

https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

So run the following command to add the device plugin to the project created.

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git


Now that we have added the device plugin to the project, let us use the Device API in our project.

We will make some simple changes to test if the functionality related to Device API is working or not.

Modify your onDeviceReady function in index.js file of your <Project Name>\www\js directory to display the information related to device. 

The modifications(in red) are given below.

 onDeviceReady: function() {
        app.receivedEvent('deviceready');
 var element = document.getElementById('deviceProperties');
        element.innerHTML = 'Device Name: '     + device.name     + '<br />' +
                            'Device Cordova: '  + device.cordova  + '<br />' +
                            'Device Platform: ' + device.platform + '<br />' +
                            'Device UUID: '     + device.uuid     + '<br />' +
                            'Device Model: '    + device.model    + '<br />' +
                            'Device Version: '  + device.version  + '<br />';
    },

Now we will make modifications to index.html file in <Project Name>\www\ folder to display the device information retrieved from the above functions.

<div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
<p id="deviceProperties">Loading device properties...</p>
            </div>
<div>

Now we will add android platform running the below command

cordova platform add android



After adding the Android platform, we will build the Android project and then launch the project in emulator running the below commands.

cordova build android

cordova emulate android

The emulate command will install the application and launch the project in the emulator. 



As you can see from the above screen shot , the application is launched on the Android emulator. 

Don't worry about some of the information displayed there. Device model is not correct as it is an emulator and hence no model and device name is depreciated which is to return same thing as device model. And yes, the device Cordova which is expected to display Cordova  version is incorrect. This is a bug in Cordova 3 which is fixed in patch releases later.

So we are able to add a core Device API to the Cordova 3 project , make changes to the html and javascript files to use the functions from Device API and create a Android project, build and launch the Android project using Cordova Device API.

Now we will add another third party Cordova plugin to the project we created.

Barcode scanner plugin



The Barcode scanner plugin is available the following link.


Run the below command to add the Barcode scanner to the project.

cordova plugin add https://github.com/wildabeast/BarcodeScanner




Now we will use the functionality from this barcode scanner in project we created.

Add a button to trigger the bar code scanner in index.html file of <Project Name>\www\ folder.

The lines of code that needs to be added are indicated  in red. The other lines are already there either from the project creation or from the previous modifications.

 <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
<p id="deviceProperties">Loading device properties...</p>
            </div>
<div>
     <button id="btnStart">Start Barcode scanner</button>
</div>



Add the reference of button to the index.js file at <Project Name>\www\js directory.

The lines of code that needs to be added are indicated in red. The other lines are already there either from the project creation or from the previous modifications.

 onDeviceReady: function() {
        app.receivedEvent('deviceready');
 var element = document.getElementById('deviceProperties');
        element.innerHTML = 'Device Name: '     + device.name     + '<br />' +
                            'Device Cordova: '  + device.cordova  + '<br />' +
                            'Device Platform: ' + device.platform + '<br />' +
                            'Device UUID: '     + device.uuid     + '<br />' +
                            'Device Model: '    + device.model    + '<br />' +
                            'Device Version: '  + device.version  + '<br />';
 var btnStart = document.getElementById('btnStart');

    },

Add this code at the end of the file.

 btnStart.addEventListener('click', function(){
            cordova.plugins.barcodeScanner.scan(
      function (result) {
          alert("We got a bar code\n" +
                "Result: " + result.text + "\n" +
                "Format: " + result.format + "\n" +
                "Cancelled: " + result.cancelled);
      }, 
      function (error) {
          alert("Scanning failed: " + error);
      }
   );
        });

Now we have added the bar code scanner plugin, added a button to trigger the barcode scanning and code to trigger the barcode scanner plugin up on clicking the button.

Now we need to remove the existing Android platform , add the Android platform again and then build the Android project and the application again which are almost similar steps we followed earlier.

cordova platform rm android
cordova platform add android
cordova build android
cordova emulate android

And the application will install the application on the emulator and launch the application in the emulator.


Click on the 'Start Barcode Scanner' button to start the bar code scanner plugin.


Since this is an emulator , we cant scan the bar code , but if you are running it on actual Android device, you should be able to scan the barcode.

So i will cancel the action on which the application will show the below message. But if did scan a barcode on Android , you will see the result in this screen.



If you import this project into eclipse, you will see similar errors as observed in the previous blogpost which needs to be fixed by selecting latest Android version in the eclipse configurations.

Sunday, September 15, 2013

Installing Android Studio and creating a new Android project on Android Studio.

Android Studio IDE is launched at Google I/O 2013. Android Studio is based on  Intellij IDEA which aims to replace Eclipse + Android Developer Tools for Android development. And since Google itself is pushing it, it may catch up with eclipse soon.

Android has its pros and cons compared to eclipse.

+ Android Studio has better support for UI design and coding which comes handy when supporting devices of multiple resolutions.

+ Android Studio also has built in ProGuard and app-signing capabilities.

- As of now Android Studio cannot manage multiple projects in the same window. It opens a separate window for every project. I guess this is from Intellij IDEA and may not change soon.

- Gradle-based build support, but for users migrating from Eclipse this will be a learning curve.

Assuming Android SDK is already installed on your system,Download the latest version of Android Studio from Android Developer site. If not download the Android SDK.

http://developer.android.com/sdk/installing/studio.html


Launch the downloaded EXE file, android-studio-bundle-<version>.exe.
Follow the set up wizard instructions to complete the installation.


If JDK is not installed on your system, you will need to install latest version of Java also. Also you will need to set the system variables JDK_HOME and JAVA_HOME.


Choose whether you want to limit the installation for only your profile or all the users using the system.


Select the installation location.







Once the installation is completed, launch the IDE by clicking on the Android Studio from Programs.

Android Studio will launch displaying the below splash screen. It will take few seconds to launch the IDE.




Some times the Android Studio(mostly on older versions) may fail to launch displaying the following error.


To work around this issue, launch the Android Studio as Administrator.

In Android home screen, Select Configure --> Project Defaults --> Project Structure -- Android SDK and configure the paths to your JDK and Android SDK.



In the Android Studio home screen, click on 'New Project'.


Once you click on 'New Project', Android Studio will display the below screen for you to provide your application name, module name and package name. Also you can specify the Target SDK, Minimum required SDK, and the Android SDK version with which the application needs to be compiled with. And you specify one of the Android Studio's built in themes.


Next you will need to select the icons that will be displayed when the app is installed on devices. For now, let us leave them as it is and continue by clicking on Next.


Then you need to select which type of activity that needs to be created. Select the activity and click on Next. If you don't know which activity to choose, leave the Blank Activity as it is.


Change the activity names with your preferred activity names and click on Finish.


It will take some time to set up the project first time, since IDE will download several dependencies for gradle and indexing the project etc.


Click on the Run button from the IDE, to start running the project.


Then IDE will prompt you to select a device or emulator from the available list of devices or emulators configured on the system.


Here I have a android emulator android_2_3_3 configured on my system and I select that Android Virtual device and click on Ok.

It will take painfully long time to launch the emulator, if it is not launched earlier. It is recommended to start the emulator manually and choose that emulator from 'Choose a running device' option.




The HelloWorld application we created will be installed into the emulator/device and will be launched.



Monday, September 2, 2013

Build Library Manager using mgwt : Requirements and why mgwt ?



In the previous blogposts we have seen how to create mgwt and cordova projects and configure them in Android and iOS environments.

I was thinking about a demo mobile app for this blogpost series,and I thought library manager would be a good one.It is a perfect utility app and also we can develop it as a hybrid app. As we discussed in earlier blogposts, hybrid apps are best suitable for productivity and utility apps.

I read a lot, and there are my family members and colleagues who share the same passion.We normally share books, and so times we end up buying same books.So I thought developing a library manager which keeps track of the books read, books which I wish to read would be a good use case for this demo app.

Library Manager Requirements


  • The high level requirements for this library manager demo app are:


      1. App will display all the books that
      2. I own.
      3. I borrowed.
      4. I read.
      5. I wish to read.


  • App will allow the users to add new books with the following information.


      1. Book Title
      2. Author name
      3. Publisher
      4. Category
      5. Edition
      6. ISBN Code
      7. Book Type
      8. Status
      9. Recommendation
      10. Feedback



  • Users will also be able to modify the book information.


  • The below mock ups are self descriptive of the functionalities we want, but we may take the liberty of deviating a little bit from these mock ups if required.


  • Now we know the requirements of the app we want to build and so let us decide on the technology stack or the frameworks we would use to build this app.


  • Since we have decided on using Apache Cordova, the final deployable code needs to be in javascript. But coding bigger apps in javascript is not easy. 
  • Javascript is an interpreted programming language with dynamic typing. While it is fast, developers lost all the advantages of a static,strong and safe languages like Java.And javascript doesn't have good tool support like Java or .Net had.
  • Wouldn't it be great if we can combine the best of javascript with the best of static, strong and object oriented languages. Yes ? 


  • If you are some one like me, who is trying to web development from java experience. The options seem to be few.


JSF:


Pro


  • Creating facelets xhtml components is simple, which promotes re-use.
  • Decent templating abilities using built in tags like ui:insert, ui:include, and ui:decorate
  • Simple access to Spring beans through faces-config
  • XHTML based so web developers unfamiliar with java can still be effective
  • Allows get requests and bookmarking
  • Has built in Ajax support

Con


  • But if you want exquisite javascript behaviour, you'll have to write some javascript
  • JSF tracks the current UI state in client or server-side. This is a tradeoff between network traffic or server memory.


GWT


Pro


  • If you are a Java Programmer with experience in Swing or AWT, then there is bare minimum learning curve to start using GWT. Even if you don't have UI development experience using Java, you can still work on the server side components.
  • The major work is done on the client side, and so the response of the servers will be better.GWT follows the concept of stateful client and stateless server.
  • It takes care of all the cross browser compatibility issues.
  • There is good IDE support for GWT since you code in java, and there are a good number of IDE's for java. Eclipse, IntellJ Idea and Netbeans, all major Java IDE's support GWT framework explicitly. With this you have all the advantages of using an IDE, like refactoring, Debugging, auto complete code, syntax help, compilation errors etc.
  • The code is written in Java and GWT compiler compiles it into JavaScript. And GWT compiler can consistently generate a code which is optimized for specific browsers. Say if you want to run your web app on IE9, then there is specific permutation available while compiling which produces the best possible javascript for that browser. GWT compiler also ignores the unwanted dead code and also obfuscates the javascript.
  • There is an inbuilt browser back button support even with Ajax.
  • You can use the available unit testing frameworks like JUnit and TestNG for unit testing.
  • You can use all the helpful java tools like FindBugs, CheckStyle PMD etc which helps you in monitoring the code quality.

Con:


  • With lot of advantages on its favor, GWT has also few disadvantages against it
  • The GWT compilation is very slow. But you wouldn't do compilation very often since it GWT compilation requires only during production deployment. During the development, you can use Dev mode which works on refreshing the screen without compiling the app.
  • The GUI widgets are limited, and the advanced UI widgets are not available directly.You will need to extend the frame work to create the widgets you require, or integrate external widgets. Sencha and Vadding provide excellent UI widgets on top of GWT.


  • The widgets for mobile are not available.


GWT on Mobile 



  • mgwt is a mobile gwt framework developed by Daniel Kurka, who is also a member of GWT steering committee,and the source is open sourced.
  • mgwt is built on top of gwt and so all the advantages in GWT will still be available.
  • mgwt provides lots of mobile widgets and animations which are required for developing mobile applications.
  • mgwt works with GWT designer and UI Binder. There are different themes for iPhone, iPad, Android Phones, Android tablets. So the look and feel of the app which change based on the device the app is running on.
  • mgwt provides touch event and animation event support on top of GWT. Mouse input and finger touch are considered in the same way and so you can run the code on the desktop browser and check for issues before actually running it on mobile browsers.
  • mgwt adds touch event support and animation event to GWT by adding a custom DOM implementation. Mouse input is treated as one finger touching the device, so you don´t have to write code to handle both mouse and touch.
  • Most of the styling,layouts and animations in mgwt is done using more css and no graphics. So the size of the app is small, there by reducing the start up times or loading time.
  • The useful features of GWT like Model-View-Presenter architecture, Deferred binding and client Bundles are supported by mgwt and so GWT compiler can produce the most optimized code of your app.
  • During the compilation, GWT compiler can remove the unwanted css. So the application performance will be fast.


These advantages make me believe that mgwt is the apt for the app we intend to build. So we will start building the app using mgwt. As and when I encounter new information, I will be writing about that.

In the next blogpost I will start creating the UI as per the mock ups.


Sunday, September 1, 2013

Deploy your existing mgwt app on Android using Apache Cordova 3

In the previous blogposts we have seen on how to create a new project using Apache Cordova 3. In this blogpost we will see how to package the existing mgwt project into an Android application using Apache Cordova 3. In fact,you can substitute any UI framework in place of mgwt, and the remaining process is going to remain same.


  • If you already have a mgwt project import that project instead of creating a new one. You can skip the below steps until you create a Cordova Android project.
  • Launch your eclipse and create a GWT web project.
  • Add mgwt-1.1.2 or latest version of mgwt to your project classpath. 






  • If you created a new project just remove all the code and use the simple code below in the EntryPoint class.


public void onModuleLoad() {
final Button sendButton = new Button("Send");
final MTextBox nameField = new MTextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();

// We can add style names to widgets
sendButton.addStyleName("sendButton");

// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);

// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
}


  • We just wanted to deploy this app in Android and see our code working, so lets keep it as simple as possible.


  • Add the following lines to the gwt.xml file in your project.


<inherits name="com.googlecode.mgwt.MGWT"/>
<set-property name="user.agent" value="safari" />



  • And then compile the project.




  • In the war folder, you will see the compiled javascript with in the folder name which is same as the project you created. 
  • Here I created a mgwt project cordova3Android and so all the compiled javascript is in war--> cordova3android and Cordova3Android.html is my index file.
  • Now we will create a Cordova project. Launch the command line , and run the below command.


                                  cordova create Cordova3Android



  • This will create a Cordova project Cordova3Android.
  • The www folder of Cordova3Android project looks like the below. It consists of the default files created by cordova.








  • Now copy the javascript and html files from your project into the www folder in Cordova3Android project.






  • If the index file of your project is some thing else other than index.html file, then you need to change that in the config.xml file. By default index.html will be configured as the application home page.





  • Change the mapping in 'Content src' tag to point to your application home page. In this case the application home page is Cordova3Android.html and so modify the config.xml to apply this change.



  • Save the Config.xml file and now create the platforms you want this application to be deployed on.
  • The steps till this point are same irrespective of the platform you are planning to build for.
  • Till this point there are no platforms defined and so the platforms folder in your application folder is blank.



  • Now change your command line working directory to this project and add the Android platform running the following command.


cordova -d platform add android




  • Cordova copies all the files required for creating an Android project and creates an Android project from the root project you have created.




  • Now build the created project running the below command.


cordova build


  • And launch the project on Android running the below command. 

cordova emulate android



  • cordova will launch the Android emulator, and you can see your changes in project once the application is launched in the emulator.



  • So we have imported an existing mgwt project into Apache Cordova 3 build. 
  • Please note that the platforms need to be added after all your project changes are applied to the root project.
  • Now you will make changes to your app and redeploy it again. I will just change one line in the gwt project. The string in red below is the only change in the project and so the emulator when launched should show 'Coding Square' instead of earlier 'GWT User'.
                              nameField.setText("Coding Square");

  • Now compile the project. And on the command line remove the Android platform by running the below command.
 

cordova platform rm android



  • This will delete the Android platform.
  • Now copy the compiled javascript to the project root 'www' folder. And create the Android platform again.

cordova -d platform add android


  • Now build the project and launch the emulator to view your changes.

cordova build

cordova emulate android




  • So we are able to see 'Coding Square' as expected in the text box instead of the 'GWT User'
  • As of now there doesn't seems to be a way to rebuild the project from root without deleting and recreating the platform.