Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Build a Hybrid Mobile Application With Android

DZone's Guide to

Build a Hybrid Mobile Application With Android

In this tutorial, you'll learn how to implement a simple Android hybrid application

· Mobile Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

We’ll start off with a basic Android project, and show how to add Hybrid components that can be implemented in any existing Android app! For a video version of this tutorial, scroll to the bottom of the page.

There are two main components to a hybrid app: native code (Java and the Android frameworks), and also the web code (HTML/CSS/JavaScript). We’ll focus on the Android side of things, and cover what both sides need to do in order to communicate seamlessly with one another.

To learn a little more about what Hybrid means, check out this blog post and video.

In this demo, we’ll be creating a basic mCommerce experience. The user can browse a list of products that are displayed within a WebView, while the cart and checkout flow are handled natively. It’s a common use case, and perfect to show off the benefits of each platform.

Let’s get started!

hybrid-demo-and-1

Android

At a minimum, we need a native shell to hold the web side of our app. Our demo will be about 30/70 web/native, so we’ll need to do some setup and native implementation. However, keep in mind you can make your app any combination of web/native – it’s all up to you and your use case!

Get the code

First things first, grab the source code here. The demo branch has gaps in the code that we’ll fill in throughout this tutorial if you want to follow along. Otherwise, check out the master branch and you’ll have all the completed code ready to go.

Set up the Android project

The demo app shell has most of the UI already set up. There are two tabs, or fragments, the ShopFragment and the CartFragment. The ShopFragment hosts the WebView, so we’ll show how to set that up here.

Adding a WebView

Open res/layout/fragment_shop.xml in your editor of choice. Enter the code below within the RelativeLayout tag:

<WebView
android:id="@+id/shop_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />

The code is simple, and creates a full-screen WebView within its container. Notice the android:id definition, which we’ll use to bind this UI element in our code.

hybrid-demo-and-2

Setting up the WebView in code

Next, we’ll finish setting up the WebView by editing the ShopFragment.java file. Within the onCreateView method, insert the following code in Placeholder 1:

mWebView = (WebView) rootView.findViewById(R.id.shop_webview);

This binds the mWebView class variable to the UI element we just created in our layout. Now that we can access the WebView from the code, we can load a URL into it. To do that, enter the following code in Placeholder 2:

mWebView.loadUrl(APIRequest.BASE_URL);

If you check out APIRequest.BASE_URL, you’ll notice a web URL – that’s the URL that will be loaded into our WebView, but you can check it out in your desktop browser as well.

Run the app to see what we have so far. Poke around the products, and jump over to view the cart. You’ll notice the ‘Add to Cart’ buttons don’t quite work, but we’ll get to that later

Web

In this demo, the web component displays all the products in a browsable interface. The project happens to be built on the Django web framework in Python, with the front-end built in HTML/CSS and Javascript. There are a few APIs as well, all created for demo purposes – so they’re simplified as much as possible. Keep in mind you can use the web frameworks of your choosing, we just happened to pick Django and standard JavaScript.

Get the code

As with all mind-blowing demos, the code is also open-sourced so you can download the web side and tinker with it yourself. Check out the Github project to download the web code in its entirety.

Note: The web code is in a different repository than the native code mentioned earlier

Run it locally

If you wish to run the web code locally, you certainly can! Check out the Django docs to learn a bit more and get everything installed and running on your local machine.

We deployed this demo code to Heroku at http://critterretail.herokuapp.com/. You can change the URL the project uses in APIRequest.java in the BASE_URL variable if you wish to point it to your own instance.

Note: If you’re running the server locally in the Genymotion emulator, make sure to use the BASE_URL of http://10.0.3.2:8000/

Connecting Web & Android

Now we have code running in two different platforms, on the web and also on Android – all within the same app. To create a great experience for our users, we’ll need to link these platforms in some way.

In our demo app, when you add a product to the cart (in the WebView) – it loads the item into the native database for checkout (on the Android side). We’ll show what needs to happen on both sides to accomplish this!

hybrid-demo-and-3

On the web side

In the web code, if you open critterretail/templates/index.html you’ll see a link on line 36-37. This is the key to communicating with the Android app:

<a class="btn btn-success" style="width:100%;"
href="apprequest://addtocart#{{p.productJSON}}">Add to Cart</a>

What happens when you click the link is a redirect to a url that looks like:

apprequest://addtocart#{'productID':4}

The JSON is rendered by the python code, and is dependent on which button was clicked – making this request dynamic.

You’ll notice the url is not an http:// request but rather an apprequest://, and there’s a good reason behind that. Let’s head back over to the Android code to bring it all together.

On the Android side

Open up ShopFragment.java and head down to the onCreateView method. You’ll find an unimplemented WebViewClient. Replace Placeholder 3 with the code shown below:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

// Example request apprequest://addtocart#{'itemID':1}
if (url.startsWith("apprequest://")) {
Uri uri = Uri.parse(url);

// example host == apprequest
String command = uri.getHost();

// example fragment == {'itemID':1}
String jsonString = uri.getFragment();

try {
// parse the fragment and handle the full request
JSONObject json = new JSONObject(jsonString);
handleRequest(command, json);
} catch (JSONException e) {
Crittercism.logHandledException(e);
}

return true;
}
return false;
}

There’s a lot going on here – but the method we’re overriding is called each time a URL is about to be loaded within the WebView. By intercepting this, we can look out for custom requests (i.e. requests that start with apprequest:// instead of http://) and handle them separately.

By reading through the code comments, you can note how the URL is parsed and how to create your own custom requests on the web side. Scroll up to view the handleRequest method to modify or add new commands!

Run the app once more and add an item to the cart, and it works! The web app within the WebView is successfully talking to the code in the native view.

hybrid-demo-and-4

Cross-platform Performance Monitoring

Tracking issues is hard enough on one platform – but once you leverage multiple platforms within the same app it can be very tricky to figure out performance bottlenecks in your application. Fortunately, Crittercism’s App Intelligence solution provides insight into both the web and native sides of your app, and it’s already implemented within the demo!

From crash reporting and exception handling to API service monitoring and business transactions, you can now achieve visibility into the performance of the native and web components of your hybrid application from a single, integrated solution.

Wrapping up

With this tutorial, you can take an existing Android app and add hybrid components to it. With the ability to share data back and forth between the web and native platforms, you can create all kinds of nifty use cases – so get out there and start building!

If you’d like to download the completed code from this tutorial, you can do so by checking out the master branch of this Github project.


Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:
android ,hybrid mobile apps

Published at DZone with permission of Chris Beauchamp, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}