Telerik blogs

With the launch of Kendo UI Mobile this month (have you downloaded it yet?), we introduced a completely new development philosophy into the arena of HTML5 development on mobile devices.

What If

What if you could develop one native application and target multiple devices? Too good to be true? Usually. But with Kendo UI Mobile we close the gap between dream and reality. For the first time, you can develop cross platform HTML5 applications that automatically adapt to the native look-and-feel of the mobile device where they are running. Develop one application and then deploy it to both iOS and Android devices without changing one line of your code, while still delivering a native experience to users on both platforms.

Let's take a look at how we can build a very simple native HTML5 application with Kendo UI Mobile and PhoneGap that will have you up and running in no time flat.

Estimated Time To Complete: 20 Minutes

Application Description

Our application is a conference tracker. It allows a user to track a conference schedule and additionally lets the organizers target alerts at users.

The final app looks like this...

finished1    finished2

The Setup

You can do this exercise on either a mac or a pc, but if you want to deploy your application to the iOS simulator, you will need to be on a mac. I will be demonstrating on a mac since I can target both android and iOS from the same machine.

Prerequistes

Before you begin this exercise, make sure that you are setup to build either iOS or Android native applications.

iOS: For iOS, that means installing XCode 4 from the App Store. It's pretty straightforward and needs not much more explanation than that. Remember, you must be on a Mac to install XCode.

Android: For Android, you will need to download the SDK, install Eclipse and then install the Android Development Tools (ADT) for Eclipse. There are excellent instructions on getting your Android environment setup.

Now that we have the prereq's out of the way, lets get started.

Step 1: Download the Kendo UI Mobile Bits

Download Kendo UI Mobile here if you have not already. Go ahead and unzip this and take mental note of the directory. For right now, it doesn't matter where you unzip the contents as long as you remember where you put them.

phonegap

Step 2: Download PhoneGap

Download PhoneGap here. One PhoneGap install contains everything you need for both iOS and Android.

Step 3: Install PhoneGap

Installing PhoneGap will create project templates for both iOS and Android. I'm going to build on iOS for a native application, then we'll see how easy it is to deploy this project to the web and get a native experience on Android as well.

Step 4: Create a new PhoneGap Application

There are some superb instructions from the PhoneGap folks on creating your first project.

Once you have that first project created, you can fire it up in the emulator, and you should see something like the following image to the right here.

Step 5: Add Kendo UI Mobile Scripts/CSS

Now copy the Kendo UI Mobile js and styles files to the www folder in your PhoneGap project. You need to do this by coping them in Finder. Your directory in Finder should then look like this.

finder

A Quick Look At Index.html

In your www folder, open up the index.html file. There's a lot in this file, so let's have a look at the head before we add Kendo UI Mobile.

The first thing you notice is all the stuff in the head. Let's step through it. First we have an empty title element. The title is not really of any importance here as it won't be seen or used, but it's semantically correct to have a title in your html.

<title></title>

 

Next we have some meta tags

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" /> <meta charset="utf-8">

 

The first meta tag defines the viewport - or rather - how to scale the content of the page for the device. Here it is simply saying to scale the page to 1.0 which makes all of the content on the page viewable in the viewport as far as width goes.

The meta charset is required like the title so that your HTML validates. Remember, this is running in a Safari Window after all.

The next couple of lines define media query css files. One of these files will be loaded in when the device is in portrait mode, and the other will be loaded when the device is rotated and the screen goes the landscape. These lines are commented out by default, but should you need them, this is an example of how you might implement it. For our example, we don't need media queries so remove this block.

<!-- DELETE THIS -->
<!-- iPad/iPhone specific css below, add after your main css
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />  -->

 

Where we deleted the media queries block is where we will drop references to the Kendo UI Mobile CSS files. The /styles directory is relative to the root which is www. This means that the style includes look like this...

fixedall

We include the kendo.mobile.add.min.css, which contains the platform specific styles and images that are required to make this HTML5 application look completely native.

JSON2 Warning

You also have a line or warning that you need to include JSON2.js if you are targeting iOS prior to 4.0. This is the library that takes care of JSON serialization in the browser. Version 4.0 and up has it included already. In this example, I'm only targeting 4.0 and above so I deleted this line.

<!-- If your application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->

 

And finally the line with all the power! The PhoneGap.js include.      

<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>

 

It's considered best practice to put your script files at the bottom of your page so they don't block the UI from loading, but when you are building a PhoneGap application your scenario is a bit different.

Here we are going to load the whole UI and then release the splash screen when the underlying UI is done. This is one of the nice things about developing for the device, We can make assumptions like this and know that the experience will be completely acceptable for the user.

Just below the PhoneGap include, add jQuery and the kendo.mobile.min.js file. This file contains all the mobile controls. You could pick and choose which components you wanted so as to cut bloat. In the official release, there will be a download builder which will resolve dependencies for you.

For the time being and ease of demonstration, I'm going to use the complete library. We aren't really worried about size here because this is a mobile application that is going to be deployed to the device. Again, developing a native application frees you from some of the things that you would normally have to consider in web development.

My script includes look like this...

scripts

Delete PhoneGap Default Content

The last thing we need to do before we start building the application is to remove the default PhoneGap content. Remove everything inside the body tags, and remove the alert from the OnDeviceReady() event.

phonegaponready

The Fun Starts

Ok - that was a bit of setup and plumbing, but we are ready to start building our application.

As a refresher, here is the screenshot of the final application. It has two screens:

finished1

Screen 1: Home Screen

This screen holds various announcements that we might want to push to people. Since this is a native application, we can also wire up push notifications if we wanted to.

finished2

Screen 2: Conference Schedule

This is a list view by day with the available sessions. It is scrollable and grouped by day listing the time, speaker and session title.

We first need to add some HTML boilerplate to build the structure of this application. Everything inside of the Kendo UI Mobile framework is built on data attributes. Here is the layout of the application.

<div data-role="view" data-layout="app" data-title="info" id="info"><br><div id="news"> </div> </div><br><div data-role="view" data-layout="app" data-title="schedule" id="schedule"><br><ul id="sessions"> </ul> </div> <br><div data-role="layout" data-id="app"><br><header data-role="header"><br><div data-role="navbar">Conference Tracker</div> </header> <br><footer data-role="footer"> <br><div data-role="tabstrip"><br><a href="#info" data-icon="info">Info</a><br><a href="#schedule" data-icon="recents">Schedule</a> </div> </footer> </div>

 

The main container defines a "default" layout for this application. This basically defines a master view that is used on all views. We want the same header and footer for all views so we define the layout in the data-role attribute of the main container. The views themselves can sit above or below the main container layout. in this example, they are sitting above it.

The header is defined by it's role. This tells Kendo UI Mobile that this is the header of the application. Inside that header, we place a NavBar.

<header data-role="header"> <div data-role="navbar">Conference Tracker</div> </header>

 

The footer is a Tabstrip component. How does Kendo UI know that this is a Tabstrip? Look at the data-role tag. The data-role="footer" tells us it goes at the bottom. The data-role="tabstrip" tells Kendo UI that it's a TabStrip component. Inside we have a set of anchors which link to different "views". Each anchor has text and an icon, which is defined by the data-icon attribute. A complete list of icons and what they are named can be found in the Tabstrip demo (scroll to the bottom).

<footer data-role="footer"> <div data-role="tabstrip"> <a href="#info" data-icon="info">Info</a> <a href="#schedule" data-icon="recents">Schedule</a> </div> </footer>

 

Now each time we click on one of the icons in the footer, it will load in a different view. We define each of these views outside of the main "layout" container. As usual, the data-role="view" defines each of these divs as a view.

The data-layout="layout" tells Kendo UI that they are views that will be rendered into the container that has the layout data-role attribute.

notmuch

Let's run this.

That doesn't look like much, because we need to add the JavaScript that transforms this plain HTML into an iOS application.

Add The Magic

Ready? Just above the closing body tag, add the following piece of JavaScript:

<script> var app = new kendo.mobile.Application($(document).body);</script>
 

That's it! By default, it looks through the whole body of the document and makes it an application. The document.body portion is actually optional, but I'm including it because we are going to define some transitions here later and in that case we need to specify the first parameter, which is the location of the application in the DOM. kendoized

Now let's run it and have a look.

That looks like a proper iOS application!

View Transitions

When you click on the icons in the footer, the view changes. But at this point, it's just a change. iOS has great animated transitions so let's add one to the application.

All we need to do is add a transition object to our one line of JavaScript.

var application =
new kendo.mobile.Application($(document).body,
{ transition: "slide" });

 

Now the views slide in. What's more, they slide in from the direction that they left, instead of always sliding in from the same side. If a view slides out to the right, it will slide back in from the right.

Lets put some data in these views.

Wiring Up View Events

Views have two events. One event when the view is initialized, and one each time the view is displayed.

For starters let's wire up the info view – which is also the home screen. This is the screen that contains all of the announcements.

We can handle the view initialization two ways. The first is to bind to the init event on the application object and then look at each view as it is bound.

Another way is to define the function we want the view to execute on initialization by using the data-init attribute on the view. This is a pretty neat binding feature so let's go this route.

We just add a data-init="getInfo" to our view.

<div data-role="view" data-init="getInfo" data-layout="app" data-title="info" id="info">

 

Now create that function in the JavaScript. In the fuction getInfo, I'm simply making an AJAX call using a jQuery .get() to a local service running on my machine. When the data returns, I am appending it to the news div and applying some minor styling by giving it a class of info.

<script>
 // creates the application UI var application = new kendo.mobile.Application($(document).body, { transition: "slide" });
  
 var getInfo = function() {
     // read from the remote data source
     $.get("http://localhost:3000/infos.json", function(data) {
         $.each(data, function() {
             $("#news").append("<p class='info'>" + this.content + "</p>");
         });
     });
}   
</script>

 

Now if we checkout the app, you would notice that there is still no data showing up.

The reason for this is that the device is blocking our request for remote data. The output window tells you this if you take a look at it:

whitelist
See all those whitelist rejection url='http://localhost:3000/infos.json errors? That's the problem. Our remote call for data is being blocked by PhoneGap.

In order to remote data calls, we need to open up the PhoneGap.plist file in the XCode project and add an entry under the "External Hosts" option. Once we do this, we will be able to call the remote service.

plistentry

Since I'm running my service in development, my whitelist entry is for localhost. Wildcards are OK too though. So if your service was located at service.myapp.com, you could just juse *.myapp.com to accommodate all subdomains.

You can also use just * which allows all traffic. This is not recommended as it makes your application vulnerable. We are essentially doing a cross-domain request here. Only trust URL's you control.

finished1

Now we have some data in the app!

Great! Now lets move on to the schedule view.

Schedule View

For the schedule view, we're going to use another Kendo UI Mobile widget called the ListView. The ListView is something that you are probably very used to seeing. It is a scrolling list of items in the viewport. The most familiar example of this would be the Contacts application on the iPhone.

To add a ListView, we simply need to add a ul to the schedule view. Additionally, the ListView can be dynamically bound. In order to do that, we need to make the call to the remote source and bind it to the returned JSON data.

In the initialization for the view, we can select the ul, make it into a ListView by calling kendoMobileListView() and then setting the datasource.

I also specify a template for each item to add some CSS and layout to them. For more information on Kendo UI Templates, see the demos and documentation.

Here is what the HTML for the Schedule view looks like:

<div data-role="view" data-layout="app" data-init="getSessions" data-title="schedule" id="schedule"> <ul id="sessions"></ul> </div>

 

Pretty simple. Notice that we specified the getSessions method to use on initialization of the view. We need to create that method in the JavaScript.

var getSessions = function() {
    $("#sessions").kendoMobileListView({
        dataSource: kendo.data.DataSource.create({
            transport: {
                read: "http://localhost:3000/sessions.json"
            },
            group: "day"
        }),
        template: $("#sessionsTemplate").html()
    });
}

listview

 

This method selects the ul, turns it into a ListView while specifying the DataSource, grouping and template. The template is pretty simple as well.

<script type="text/x-kendo-template" id="sessionsTemplate">
    <div class="left">
        <div class='time'>${ formatted_time }</div>
        <div class='speaker'>${ speaker }</div>
    </div>
    <div class="title">${ title }</div>
</script>

 

Check it out! We have a data bound ListView grouped by day telling us the time, speaker and title of each session.

At this point, you could add more features, like the ability to add a reminder about a session to your calendar. Additionally, you could send push notifications to users once they installed the application from the app store.

Native Everywhere

Remember that we discussed early on that Kendo UI Mobile will adapt to the device? Well all we have to do to check that out is to hit the site from the web from an Android device. We will automatically get an android look and feel.

This is the exact same application running from the web in the Android emulator. Notice that without changing any code or doing any CSS black magic, the look and feel adapts to Android native.

Android1            android2

Grab The Code

I have several packages for you. The first one is the XCode project that contains the application I built in this example.

The second is a Ruby On Rails project that serves up the data for the application.

XCode Download
Rails Project Download

Thanks to Christian Weyer who ported this to an native Android application with a .NET Web API back end. You can snag those projects here off of his GitHub repository.

Eclipse Android Project
Web API Services Project

Check it out LIVE on your mobile device

Download the Kendo UI Mobile and PhoneGap and get started building your first Kendo UI Mobile native HTML5 application.


Burke Holland is the Director of Developer Relations at Telerik
About the Author

Burke Holland

Burke Holland is a web developer living in Nashville, TN and was the Director of Developer Relations at Progress. He enjoys working with and meeting developers who are building mobile apps with jQuery / HTML5 and loves to hack on social API's. Burke worked for Progress as a Developer Advocate focusing on Kendo UI.

Comments

Comments are disabled in preview mode.