Showing posts with label gwt. Show all posts
Showing posts with label gwt. Show all posts

Friday, March 3, 2017

Using Cordova Network API in gwt phonegap


The Network API provides access to the network connectivity information of the device, including wifi and cellular connection status.

Configuration


For using this API, you need to add Network Information plugin to your project.

cordova plugin add cordova-plugin-network-information
The network API can be accessed in gwt phonegap project as described below.

final PhoneGap phoneGap = GWT.create(PhoneGap.class);
Connection connection = phoneGap.getConnection();


The Network API is a very simple API and provides only 1 property/method and 2 events.


Usage


connection.type


Description


This provides the type of active network connection available. The possible connection types are :
  • Connection.UNKNOWN
  • Connection.ETHERNET
  • Connection.WIFI
  • Connection.CELL_2G
  • Connection.CELL_3G
  • Connection.CELL_4G
  • Connection.CELL
  • Connection.NONE

If the device doesn’t have a active network connection, then the connection type returned is NONE.

If the device has a active Wifi connection and a active 3G/2G/4G connection, then the connection type returned will be Wifi. The devices are designed to use the most efficient network when multiple active networks are available. Since the wifi is more efficient(more reliable, stable and cost effective), the devices normally use wifi even if other cellular connection types are available. If wifi is not available, then the device will check for the next efficient cellular connection type which normally will be in the sequence 4G,3G ,2G and CELL.

Sometimes, it is just not enough to known whether the device has active network connection or not. The application needs to know what is the connection type. You may have a user preference where user decides if the app can work on Cellular network or not. In this case, you need to check the connection type to match the user preference and allow the app to work in offline or not allow the user to launch if the connection type doesn’t match the user preference.

Code

String connectionType = connection.getType();


Supported Platforms


  • iOS
  • Android
  • Windows : When running on a emulator, the connection type is ETHERNET.


offline


Description


This event is fired when the device connected to the network is disconnected.


Code


The code for registering the offline event is below.
phoneGap.getEvent().getOffLineHandler().addOfflineHandler(new OffLineHandler() {
               
                @Override
                public void onOffLine(OffLineEvent event) {
               //Add your code here.
                }
            });


online


Description


This event is fired when the device is connected to the network.


Code


The code for registering the online event is below.
phoneGap.getEvent().getOnlineHandler().addOnlineHandler(new OnlineHandler() {
           
            @Override
            public void onOnlineEvent(OnlineEvent event) {
            //Add your code here.
            }
        });


Demo


The below example demonstrates usage of the Network API.

public class ConnectionDemo implements EntryPoint {
     private Logger log = Logger.getLogger(getClass().getName());
     private ScrollPanel scrollPanel = null;
     private LinkedList<String> list = null;
     private CellList<String> cellList = null;
     private Connection connection = null;
    
    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {
         GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {

              @Override
              public void onUncaughtException(Throwable e) {
                Window.alert("uncaught: " + e.getLocalizedMessage());
                Window.alert(e.getMessage());
                log.log(Level.SEVERE, "uncaught exception", e);
              }
            });

            final PhoneGap phoneGap = GWT.create(PhoneGap.class);
            phoneGap.addHandler(new PhoneGapAvailableHandler() {
              @Override
              public void onPhoneGapAvailable(PhoneGapAvailableEvent event) {
                    createUI(phoneGap);
              }
            });

            phoneGap.addHandler(new PhoneGapTimeoutHandler() {
              @Override
              public void onPhoneGapTimeout(PhoneGapTimeoutEvent event) {
                Window.alert("can not load phonegap");

              }
            });
            phoneGap.initializePhoneGap();
    }
    private void createUI(final PhoneGap phoneGap) {
        try {
            scrollPanel =  new ScrollPanel();
            list = new LinkedList<String>();
            BasicCell<String> cell = new BasicCell<String>() {

                @Override
                public String getDisplayString(String model) {
                    return model;
                }
            };
             cellList = new CellList<String>(cell);
            scrollPanel.add(cellList);
             connection = phoneGap.getConnection();
            addInfo("Connection Type : ");
            phoneGap.getEvent().getOnlineHandler().addOnlineHandler(new OnlineHandler() {
               
                @Override
                public void onOnlineEvent(OnlineEvent event) {
                    addInfo("online and connection Type : ");
                }
            });
            phoneGap.getEvent().getOffLineHandler().addOfflineHandler(new OffLineHandler() {
               
                @Override
                public void onOffLine(OffLineEvent event) {
                    addInfo("Offline and connection Type : ");
                }
            });
            RootPanel.get("ConnectionDemo").add(scrollPanel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    private void addInfo(String type) {
        list.add(type+connection.getType());
        cellList.render(list);
        scrollPanel.refresh();
    }
}


Test


For testing, I will run this app in both iPhone 6 and Nexus 6P devices. The test steps are below.
  1. The app is launched when the device is connected to wifi and there is no cellular connectivity.
  2. Then the wifi is disabled and since there is no cellular connectivity, the device is in offline mode.
  3. The wifi is enabled.
  4. The wifi is again disabled.
  5. The cellular connectivity is enabled.
  6. The cellular connectivity is disabled.


Android Device


image

iOS Device



image

The code is available on the github.

Monday, February 27, 2017

Using Cordova Device API in gwt phonegap

 
Cordova Device API provides access to the device hardware and software information like what is the OS the device is running, its OS version and Serial id etc..

Configuration


This is a global object and is accessible any time after the deviceready event is triggered.

For using this API, you need to add the Cordova Device Plugin to the project.
cordova plugin add cordova-plugin-device
After your app is launched, include the below code to use any Apache Cordova API’s in the project.
final PhoneGap phoneGap = GWT.create(PhoneGap.class);
The Device API can be used only after the deviceready event is fired. So once your app is launched check for PhoneGapAvailableEvent. This event is fired once the Cordova library is successfully loaded and is ready for use.
    phoneGap.addHandler(new PhoneGapAvailableHandler() {
              @Override
              public void onPhoneGapAvailable(PhoneGapAvailableEvent event) {
                   // start your application code here.              }
            });
The Device API can be accessed through the Device object. The Device Object can be accessed as below

Device device = phoneGap.getDevice();

Usage


platform


Description


This property returns the operating system the device is running.
iOS devices return iOS while the Android devices return Android.

Code

String platform = device.getPlatform();

Supported Platforms


  • Android
  • iOS
  • Windows

version


Description


This property returns the device Operating system version number.

Code

String version = device.getVersion();

Supported Platforms


  • Android
  • iOS
  • Windows

cordova


Description


This property provides information of the platform specific cordova version running on the device. The cordova version and platform specific cordova  versions may be different. The cordova version displayed when you use cordova –v is the Cordova tooling and CLI version installed on your development machine.The cordova version may be 6.1, but the android platform cordova version may be 5.1 and ios platform cordova version may be 4.1. This platform specific Cordova version is the version of the cordova.js file in each platform. To get the platform specific version information from Cordova CLI, use the below command.
cordova platform list

image_thumb1


Code

String cordovaVersion = device.getPhoneGapVersion();

Supported Platforms


  • Android
  • iOS
  • Windows

model


Description


This property provides the information about the device model or product. This value is set by the manufacturer and may vary across the versions of the same product and these may not be well known names.
Ex: iPhone 6 is iPhone7,2.
On Android, this returns the product name instead of the device model.
The list of android devices product names mapping to common names is available at the below location.
https://support.google.com/googleplay/answer/1727131
And a similar list for iOS devices is available at the below url.
http://www.everyi.com/by-identifier/ipod-iphone-ipad-specs-by-model-identifier.html

Code

String model = device.getModel();

Supported Platforms


  • Android
  • iOS
  • Windows

manufacturer


Description


This property returns the name of the manufacturer of the device.
Ex: For iPhone, it would be Apple and for Samsung Galaxy Note, it would be samsung etc.

Code

String manufacturer = device.getManufacturer();

Supported Platforms


  • Android
  • iOS
  • Windows

uuid


Description


This property returns the device UUID(Universally Unique Identifier). The process of generating this UUID is different for different OS and is determined by the manufacturer.

On Android, uuid is a 64 bit integer created on first boot which is returned as string.

On iOS,uuid is created when a app from a vendor is installed. It will be same for all the apps from the same vendor. But if all the apps from the same vendor are reinstalled, then uuid will be recreated and will be different from the earlier one.

Code

String uuid = device.getUuid()

Supported Platforms


  • Android
  • iOS
  • Windows

serial


Description


This property returns the hardware serial number of the device, if available. Works only on physical devices since the emulators doesn’t have serial number.

Code

String serial = device.getSerial()

Supported Platforms


  • Android only.

isVirtual


Description


This property indicates whether the app is running on an emulator or an actual physical device.


Code

boolean isVirtual = device.isVirtual();

Supported Platforms


  • Android
  • iOS
  • Windows

Demo


The below example demonstrates the usage of the Device functions described above.

FlowPanel container = new FlowPanel();
Form widgetList = new Form();
widgetList.setHeader(new Label("Device"));
Device device = phoneGap.getDevice();
widgetList.add(new FormEntry("Platform", createTextBox(device
        .getPlatform())));
widgetList.add(new FormEntry("OS Version", createTextBox(device
        .getVersion())));
widgetList.add(new FormEntry("Cordova Version",
        createTextBox(device.getPhoneGapVersion())));
widgetList.add(new FormEntry("Model", createTextBox(device
        .getModel())));
widgetList.add(new FormEntry("Manufacturer", createTextBox(device
        .getManufacturer())));
widgetList.add(new FormEntry("Name",
        createTextBox(device.getName())));
widgetList.add(new FormEntry("Serial", createTextBox(device
        .getSerial())));
widgetList.add(new FormEntry("UUID",
        createTextBox(device.getUuid())));
widgetList.add(new FormEntry("Is Virtual", createTextBox(String
        .valueOf(device.isVirtual()))));
container.add(widgetList);
RootPanel.get("DeviceDemo").add(container);

The result of the program when it is run on different devices is as below.

Android emulator


g1_thumb1

On the Android emulator, since the manufacturer and the serial are displayed as unknown since this is a virtual device. As you can observe the device is indicated as a virtual device. Since the name of the device property is depreciated, the name value is not displayed.

Android Genymotion emulator


g2_thumb1

On a Genymotion Android emulator, the manufacturer is indicated as ‘Genymotion’ and there is no serial number as this is a virtual device and the serial number is derived from the hardware.
And similar to the other Android emulator, the device is indicated as a virtual device.
The model of the device selected in the Genymotion configuration is indicated as the model.
And the name of the device is depreciated and so no information is displayed against that.

Samsung device


Screenshot_2016-04-28-19-13-33_thumb

When the same program is run on an actual Samsung device, you see slightly different results.
The virtual status is returned as false, indicating that the device is an actual physical device.
The serial number is available since this is a real physical device.
The manufacturer name is displayed as ‘samsung’, since this is a samsung device.
The model of this device is displayed and to understand its common name, a reference to https://support.google.com/googleplay/answer/1727131 indicates that the market name of the device is ‘Galaxy Note3’.
Similar to emulator, the name is not displayed since it is depreciated.

iPhone


When the program is run on the iPhone

image_thumb4

The app is running on iPhone 6 device, so the isVirtual device flag is indicated as false.
And since name is not depreciated and serial is not supported on iOS, those values are set to blank and unknown respectively.
If we look up http://www.everyi.com/by-identifier/ipod-iphone-ipad-specs-by-model-identifier.html for iPhone7,2, we find out it is one of the iPhone 6 models.


iPad


When the app is run on iPad,


image_thumb3

The app is running on iPad device, so the isVirtual device flag is indicated as false.
And since name is not depreciated and serial is not supported on iOS, those values are set to blank and unknown respectively.
If we look up http://www.everyi.com/by-identifier/ipod-iphone-ipad-specs-by-model-identifier.html for iPad3,4, we find out it is iPad 4th Gen wifi model.


iPhone Simulator


When the program is run on the iPhone simulator:

image_thumb6

Since this is running on an emulator, the virtual flag is indicated as false and the name and serial are not supported on iOS and since this is a emulator, the model is indicated differently.

         The code displaying the usage of this API is available on github.








































Tuesday, July 15, 2014

Setting up development environment for GWT

Introduction

This is part of series intended to develop cross platform mobile applications in Java. In this blog post we will see what GWT is and set up the development environment for GWT.

GWT is an open source development toolkit for developing complex browser based Ajax applications. Using GWT you can develop Rich Internet Applications(RIA) in Java which is then compiled into JavaScript and is cross browser compliant.

Some of the advantages of developing web applications in GWT are:

Since GWT apps can be developed in Java, you can enjoy all the advantages of developing in Java like auto-complete,Debugging, refactoring, code reuse, polymorphism, over riding, over loading. And Java has large set of tools for development like Eclipse, NetBeans,JUnit and Maven etc which you can use for developing Rich Internet Applications(RIA).

Maintaining large JavaScript projects is not easier when compared to Java projects. But you need JavaScript to run Rich Internet Applications in browser. GWT combines both the advantages. You develop the applications in Java and then they are compiled into JavaScript, so you are having best of both.
GWT is almost similar to AWT and Swing packages in Java and so has a low learning curve for Java Developers.
Supporting several browsers in the market is a difficult tasks. Each browser creates it own set of problems. GWT solves this problem by creating optimized JavaScript code for each browser specifically addressing the issues with that browser. So you can support almost all the major browsers including Android , iPad and iPhone based browsers without worrying about quirks for each browser.

Developing UI's in Java is difficult task compared to other aspects of Java programming. GWT solves it by providing several UI widgets and also you can extend the existing widgets and create your own custom widgets if you wish to.

Some of the limitations of GWT are:

Since the java code is compiled into JavaScript which runs on the browsers, the JavaScript needs to be enabled on the browsers. The applications will not work if the JavaScript is not enabled on the browser.
If you have specialist UI designers who can create HTML pages, this will not work. You may have to implement what ever Designer created again in GWT.

Web Pages created by GWT cannot be indexed by search engines since these applications are generated dynamically.

I think except the second drawback in the list, others don't matter much. It is difficult to provide a rich internet application just in HTML. You will need JavaScript to create rich internet applications. Some apps provide a limited version of apps which work if JavaScript is disabled but majority of apps require JavaScript , so you are not the one there. And there is no reason why large number of users will disable JavaScript on their browsers.

And there is a work around for indexing by search engines. The index page can be created in html, and the remaining pages can be created in GWT. GWT provides an option to define index page in html format. So the index page can still be indexed by search engines and the other pages are mostly dynamically created data, so they don't need to come up in the search unless you they are some kind of content management systems(CMS).

Like the case with all the frameworks, GWT doesn't solve all the issues, but it surely makes the java developers more productive developing the web applications, provides cross browser support and works perfectly for complex enterprise web applications.

GWT Development Environment Setup

We will start setting up the development environment for GWT applications.

Java

Since you will developing the applications in Java before they are compiled into JavaScript, you need to set up Java development environment.
Once Java environment is set up, let us configure the environment for GWT.

GWT SDK:

Download the latest version of GWT SDK from the GWT project site.
http://www.gwtproject.org/download.html

gwt_1

Go to the above link and click on ‘Download GWT SDK’ highlighted in the above screen. Then unzip the downloaded GWT SDK to your preferred location on your hard disk and it will look similar to the below screen shot.

  101

You might want to add this path to use the commands available in gwt.

Right click on ‘Computer’ on your desktop and select ‘Properties’ which displays the below screen. Click on ‘Advanced System settings’.

a5

Click on ‘Environment Variables’ in the below screen.

a6

Clicking on Environment Variables will display the below Window. Select ‘Path’ from the list of available variables and add the path to which you extracted GWT SDK.

a7

z1 
Then click on ‘OK’ to close the ‘Edit User Variable’ screen and ‘OK’ in ‘Environment Variables’ and ‘System Properties’ window to save the modifications.

 

Eclipse


You need to install the eclipse plug-in for GWT to develop GWT applications on eclipse easily. To install GWT eclipse plug-in , launch eclipse , go to Help –> Eclipse Marketplace

111

Search for GWT in the eclipse market place.

122

Find out ‘Google Plugin for Eclipse’ and the version number should match the version of the eclipse you are using. If you are using Eclipse Kepler(eclipse 4.3), you need to look for ‘Google Plugin for Eclipse 4.3) and click on ‘Install’.

124

Accept the license and click on ‘Next’ to continue installation.

127

It takes some time to download and install the plug-in.

129

While installing you will get a security warning. Just click on ‘Ok’ to continue the installation.

130

Restart the eclipse after the installation of plug-in is completed. After restarting the eclipse, you will see the GWT plug-in added to the eclipse tool bar.

131-1

NetBeans

If NetBeans is your preferred IDE, there is an GWT plug-in available for NetBeans as well.
Launch NetBeans, and in NetBeans ‘Start Page’ click on ‘Install Plugins’.




n1

Alternatively you can navigate to Plugins view by selecting Tools – > Plugins from the NetBeans menu.


n20

In the Plugins Windows, navigate to ‘Available Plugins’ tab.

n2

In the Search textbox, enter gwt and hit Enter. This will return the gwt related plugins for NetBeans.

n3

The GWT plug-in for NetBeans in GWT4NB which is the only GWT plug-in available in the list. So select it to install and click on Install button at the bottom of the Plugins screen.

n5

Click on ‘Next >’ button to start the installation of the GWT NetBeans plug-in.

n6

Select the check box against the license agreement and click on Install to agree to the license agreement and to start the installation process.

n7

GWT NetBeans plug-in is being installed..

n8

When the below message is displayed, just click on Continue to continue the installation process.

n10

Restart the IDE once the installation is completed by selecting against the ‘Restart IDE Now’ and clicking on ‘Finish’.

n11

Once the IDE is restarted, from the NetBeans Menu bar , select File –> New Project. You will see the below New Project window which has a GWT option under the Categories indicating that the GWT Plugin for NetBeans is installed successfully.

n21

Browser Plugins


And we need to install extensions to the browser you are planning to use for running the GWT app in development mode. We will see later what the development mode is, but for now let us install the plugins for the browser to complete our set up of the development environment. If you launch the app in Dev mode without installing the plug-in, the browser will display a message similar to below.

In Internet Explorer:

144-1

On Chrome:

147-1

When you click on Download, On Chrome, you will be redirected to the Chrome extensions page from where you can install the GWT Developer plug-in.

146

Click on ‘FREE’ button to install the plug-in on Chrome browser.

On IE, clicking on ‘Download’ button will download a ‘GWTDevPluginSetup.exe’ set up and launching it will install the GWT developer plug-in for IE.

Restart the browsers after the GWT developer plug-in is installed.

Unfortunately the latest versions of Mozilla Firefox doesn't support the GWT Developer Plugin. So you can’t work in Development mode on latest version of Firefox, but GWT already provides a super dev mode which doesn’t require installing any plug-in during development. So you can use Firefox in super dev mode during development mode.

Conclusion

We completed setting up the required development environment for developing applications in GWT. We can start creating GWT applications !!

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.