Translate

Wednesday, June 22, 2011

How to use web database feature of HTML5? HTML5 + Web Database + Java Script + Android + Chrome

I have created a HTML5 sample which demonstrates how to use web database.

In following sample, jquery and jsapi are being downloaded from internet on the fly at run-time. So make sure you have internet connection when you test the sample. Otherwise, you can download both jquery and jsapi from source and copy them in some local folder then load jquery and jsapi scripts from local folder.

HTML5 web database sample is as follows:
<!DOCTYPE html>
<html> 
  <head>
    <title>Offline Contacts Store using HTML5 Web Database</title>
    <script src="http://www.google.com/jsapi"></script>
    <script>
      google.load("jquery", "1.4.1");
    </script>
    <script>
      var db = window.openDatabase("contacts", "", "contacts", 1024*1024);
     
      if (db == null) alert ("Database not found DB: " + db);

      function insertRecord(number, name, email) {
       db.transaction(function(tx) {
          tx.executeSql('INSERT INTO contacts (number, name, email) VALUES (?, ?, ?)', [number, name, email]);
       });
      }
     
      function renderResults(tx, rs) {
        e = $('#search_results');
        e.html("");
        for(var i=0; i < rs.rows.length; i++) {
          r = rs.rows.item(i);
          e.html(e.html() + ' number: ' + r['number'] + ', name: ' + r['name'] + ', email: ' + r['email'] + '<br />');
        }
      }

      function renderContacts(name) {
        db.transaction(function(tx) {
          if (!(name === undefined)) {
            tx.executeSql('SELECT * FROM contacts WHERE name = ?', [name], renderResults);
          } else {
            tx.executeSql('SELECT * FROM contacts', [], renderResults);
          }
        });
      }

      $(document).ready(function() {
        db.transaction(function(tx) {
          tx.executeSql('CREATE TABLE IF NOT EXISTS contacts(number INTEGER PRIMARY KEY, name TEXT, email TEXT)', []);
        });

        $('#contacts_form').submit(function() {
            insertRecord($('#number').val(), $('#name').val(), $('#email').val());
      
          renderContacts();
          return false;
        });

        $('#filter_results_form').submit(function() {
          e = $('#filter_by_name').val();
          renderContacts(e);
          return false;
        });

        renderContacts();
      });
    </script>
  </head>
  <body>
  <h2>Contact Details</h2>
    <form method="get" id="contacts_form">
      <ul>
      <li>
        <label for="1">Contact Number</label>
        <input type="text" id="number" name="number" size="30"  />
      </li>
      <li>
        <label for="2">Name</label>
        <input type="text" id="name" name="name" size="30" placeholder="Enter Name" size="30" />
      </li>
      <li>
        <label for="3">email</label>
        <input type="email" id="email" name="email" placeholder="Enter your email address" size="30"/>
      </li>
      <div>
        <input type="submit" value="Insert Contact" />
      </div>
      </ul>
    </form>
    <div>
      <h2>Search Results</h2>
      <form id="filter_results_form">
        <input type="Name" placeholder="Filter by name" size="30" id="filter_by_name" />
        <input type="submit" value="Search Contact" />
      </form>
    </div>
    <div id="search_results">

    </div>
  </body>
</html>

Sample creates database if not available. Creates table if not already created and performs INSERT and SELECT queries on the table. Soon I will update sample with UPDATE and DELETE query samples too. UI does not look good but it does the job.

Most Android browsers support web database. I tested above sample on Android 2.3.3. To test sample on Android, deploy above sample in some web server and hit the page from your Android browser or WebView sample I have posted in previous blog: http://rashidnoorani.blogspot.com/2011/06/how-to-run-html-5-app-from-android.html

Note:
I tested above HTML5 sample in Chrome 12.0.742.100 version. Web database is not supported in Firefox 5. Sample gives "window.openDatabase is not a function" error in FireFox 5.

Monday, June 13, 2011

How to run HTML5 app from Android app? Android + WebView + HTML5 + Java Script + Web DB

I was trying to make HTML 5 sample run from Android app. I was trying to use local database feature of HTML 5 app which works well with my Android 2.3.3 version device.

Following code worked for me:

WebView webview = (WebView) findViewById(R.id.webview);

webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onExceededDatabaseQuota(String url, String
databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(estimatedSize * 2); // try to keep quota size as big as possible else database will not get created in HTML 5 app
}
});

WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setDatabaseEnabled(true);

String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);

Issue: I was using following java script code to create database:
var database = window.openDatabase("total", "", "main total", 1024*1024);

Some how database object in HTML 5 was always coming as NULL both in emulator and device. Same HTML 5 code was working properly in Crome browser. In the end, I drilled down to quotaUpdater.updateQuota() method, I tried various quota sizes but at the end "estimatedSize * 2" worked for me which is mentioned in above code sample.

I was actually working on hybrid android app. ( Hybrid = Android Native + HTML5) I have explained HTML5 web database example in separate blog post: http://rashidnoorani.blogspot.com/2011/06/how-to-use-web-database-feature-of.html.
Following HTML5 sample can be used to test above Android WebView sample app:

<!DOCTYPE html>
<html> 
  <head>
    <title>HTML5 Sample</title>
  </head>
  <body>
    <form method="get" id="employee_form">
      <div>
        <label for="1">Employee Id</label>
        <input type="number" min="1" id="id" name="id" size="5" step="1" placeholder="Enter employee Id" />
      </div>
      <div>
        <label for="2">Employee Name</label>
        <input type="text" id="firstName" name="firstName" placeholder="Enter employee name"  />
      </div>
      <div>
        <label for="3">Contact</label>
        <input type="number"  id="contact" name="contact" size="12"  placeholder="Enter contact number" />
      </div>
      <div>
        <label for="4">E-mail</label>
        <input type="email" id="email" placeholder="Enter email address" size="30"/>
      </div>
      <div>
        <input type="submit" value="Save Employee Record" />
      </div>
    </form>
  </body>
</html>

You can use www.html5test.com to check if specific HTML5 feature is supported by your browser.

Current web browsers support HTML5 to varying degrees. Modernizr JavaScript library built to make browser detection of HTML5 features easier. It can be used to check if certain HTML5 features required by the app is supported by the browser or not.


References:
HTML5 Database API Support in an Android WebView
Link: http://www.rohanradio.com/html5-database-api-support-in-an-android-webv

Wednesday, June 8, 2011

Getting started with MonoCross

What is MonoCross?

MonoCross is a C# .NET Model-View-Controller (MVC) framework where the Model and Controller are shared across platforms and the View is implemented for every specific platform and/or target architecture. It allows the development of both native and HTML5 web apps that share business logic and data code.

MonoCross is based on a modified Model-View-Controller pattern that enables separation of the presentation layer, (View) from the application code (Model + Controller). This modification enables portability of application code across multiple platform targets.
Source code and solution files for the MonoCross pattern, and the Best Sellers sample. Includes container projects for Windows Console, Mobile WebKit, iOS*, and Android^
*iOS projects require MonoTouch and MonoDevelop, all other platforms can be developed in Microsoft Visual Studio.
^Android projects require Mono for Android and Visual Studio Professional 2010.

Although MonoTouch and MonoDroid use the same language and development environment, they still require knowledge of the native coding conventions when building a presentation layer. MonoTouch uses the same native concepts that are used in CocoaTouch, (View Controllers and Delegates), and MonoDroid uses the same Activity based model used in native Android Java.

Container:
In order to run the shared application, you must create at least one container project that references the appropriate shared assembly, and renders the application into the targeted presentation platform. The BestSellers application is initially published with three platform containers:
• Console.Container - A Windows Console based deployment; this is the simplest example and is a good place to start in understanding the pattern.
• WebKit.Container - An HTML 5 deployment using ASP.NET and WebKit to render to small form-factor mobile devices, (iPhone, iPod, Android, etc.).
• Touch.Container - A native iOS deployment using MonoTouch.

Controller:
MonoCross controllers will be derived from the abstract MXController class. This class defines the base functionality necessary to register your controllers in your MonoCross application, and initialize your model objects for delivery to your container(s). You'll accomplish this by overriding the MXController.Load() method.

Model:
Design your model in a way that delivers only the information your audience needs at the time they need it. Less is definitely more when it comes to mobile application design. Take an "outside-in" view of your information with the device or devices you intend to support in mind.

View:
When constructing your views, MonoCross lets you take full advantage of the capabilities of your native platform. So construct your views in a manner that will present your information in a manner optimized for your deployment. MonoCross views inherit from the MXView class. The view Render() method must be overridden to implement any actions necessary to initialize and present your model information to the target platform.

Application:
Now that you have defined your model and your controllers you need to register your controllers in your shared application. The MXApplication class is an abstract super-type that contains the constructs needed to define your workflow, and register your controllers for use in your container.
To initialize your shared application you need to override the OnAppLoad() method of the abstract base-class. This method is called when your application is initialized, and contains the code necessary to establish your app structure.

Navigation:
The NavigationMap property is a collection of all the controllers necessary to render your application to your desired platform target(s). The NavigationMap is keyed using a URI template model which defines your application workflow. Each user-action will initiate a navigation based on the URI patterns defined in your NavigationMap.
This navigation paradigm is key to the MonoCross pattern, and enables tremendous flexibility in construction of your application. Controller-View combinations can be re-used at different points in your workflow by simply defining multiple endpoints in your NavigationMap with unique URI definitions.

Binding your App to the Container:
Now that your views are defined, all that remains is to initialize your application and bind it to your container. there are three steps to the process that must be completed in the Main() method, or equivalent entry point to your platform-specific container application
• App Initialization - set the view load event delegate, and initialize the MXContainer with an instance of your app.
• View Registration - register your views with your container using the MXContainer.AddView() method.
• Initial Navigation - perform an MXContainer.Navigate() navigation to the initial view of your application.

I have tried to define each component which is part of MonoCross framework. I collected above information from various sites mentioned below in resources section. MonoCross example is explained well in WIKI article UsingMonoCross link: http://code.google.com/p/monocross/wiki/UsingMonoCross

Resources:
MonoCross Home page: http://www.mobileframework.net/
MonoCross Download: http://monocross.net/
UsingMonoCross WIKI article: http://code.google.com/p/monocross/wiki/UsingMonoCross
MonoCross basic overview: http://vagabondrev.org/2011/04/20/monocross-the-technology/