Category Archives: Android

An MVC4, iOS And Android App With ServiceStack, Xamarin and C#

A bit late getting this out, but I published a new course for Pluralsight.

An MVC4, iOS And Android App With ServiceStack, Xamarin and C#

This course was really fun to create.  I got to use several of my favorite technologies.

2013 08 19 16 52 05 thumb An MVC4, iOS And Android App With ServiceStack, Xamarin and C#

Here is the course description:

It can be very difficult to build a cross platform application that will work on the web as well as popular mobile platforms like Android and iOS.

In this course, I’ll take you through the complete process of creating an application that works on each of the platforms and uses a REST based backend API to share data and business logic—all using C#.

We’ll start off this course by learning how to build a REST based API using the popular open source framework ServiceStack. I’ll show you how easy it is to get ServiceStack set up and even how to store data for the API using a Redis database.

Next, I’ll show you how to create an ASP.NET MVC 4 application that uses the REST service we built to display it’s data and implement it’s logic. We’ll learn how to use JQuery to make AJAX calls to a REST based API from within our MVC 4 application.

Then, we’ll learn how we can use C# and the .NET framework to build an Android application using the Xamarin tools. We’ll use the same REST API, we created earlier and build a real native Android application that is able to consume that API for implementing its logic and displaying data.

Finally, I’ll show you how to do the same thing for an iOS application. We’ll again use C# to build a real native iOS application with the Xamarin tools and learn how to consume REST based web services from iOS.

So, if you are a C# developer and don’t want to have to learn several other programming languages to build cross platform applications; you’ll definitely want to check out this course. By the end of this course, you’ll have the skills you need to be able to implement an end-to-end cross platform solution complete with a REST based API backend all in C#.

Introduction to MonoGame

I’ve been playing around quite a bit with MonoGame lately and thought I would take some time to write a bit about it and talk about how to get started.

I’m also currently working on a Pluralsight course on cross platform development with MonoGame.

monogamelogo100x100 thumb Introduction to MonoGame

What is MonoGame?

Well, if you are familiar with XNA, then you already know what MonoGame is.

If you are not familiar with XNA though, it is basically a game development framework that allows for creating games quickly without having to write all that repetitious code that all games need.

Basically it makes creating games more about the game and less about the technical details.

The only problem with XNA is that it only really works for Windows, XBox360 and Windows Phone 7.  If you want to create a game on Android and iOS, you can’t use XNA.

This is where MonoGame comes in.  MonoGame is an open source port of the XNA framework that can run on many more platforms that Microsoft’s XNA.

Great, so what does this actually mean?

Well, if you are interested in game development, especially if you are interested in game development for the most popular platforms today, MonoGame might be able to help you to write pretty close to the same exact code and have it work on Android, iOS, Windows 7, Windows 8, Windows Phone 7, MacOS, XBox 360, Linux and the new Playstation console.

That is pretty awesome!  Especially if you are trying to monetize your effort.

In my mind MonoGame helps overcome two huge barriers to getting into game development.

  1. Difficulty of monetizing the effort.  By allowing the same code to be shared on most platforms, a game developer can get paid for their effort in multiple marketplaces.
  2. Not knowing where to get started.  The XNA API is so simple to use that you can get a simple game, like a Pong clone for example, up and running in about a couple of hours.

Also, because MonoGame is basically just XNA, you can find a whole host of resources on how to develop a game using the platform.

In my upcoming Pluralsight course, I show how to create a Pong clone on Windows and then we get that game up and running on Android, iOS and Windows Phone 7, with minimal changes.

dgun 853 50 games pr h thumb Introduction to MonoGame

Getting started

It can be a bit challenging to find good information to get started in each platform using MonoGame, but the basics are located on the Github page.

For the Windows tutorial there, you can use Visual Studio instead and use the MonoGame installer.

For each platform things area slightly different, but really not all that hard.  If you want to have your game run in Android and iOS, you’ll need Mono for Android and MonoTouch respectively.

For Android development, you can use Visual Studio as long as you have Mono for Android installed and all you really need to do is link your files from your Windows project and create a small bit of startup code in an Android Activity to start the game.

For iOS development, you will need to use MonoDevelop, which is packaged with the install of MonoTouch.  MonoTouch itself uses XCode and the iPhone SDK, so you have a bit more installing to do there, but the idea is pretty much the same.  One you have MonoTouch running on your Mac, you can link over the files from your Windows project, add a small bit of startup code, and you are up and running.  (You’ll also need to download the actual MonoGame source code to add to your project, since there isn’t an installer for Mac currently.)

Xamarin also has a seminar they did on MonoGame to help you get started.

True cross platform development, finally

At least for game developers.  For other applications in the mobile space, there are some solutions that help you share your code, but nothing that really allows you to have near 100% portability without a big sacrifice.

I was pretty amazed the first time my game just ran on my Android and iOS devices with virtually no changes.

I’d definitely encourage you to check out MonoGame and stay tuned for my Pluralsight video on the topic, where I will go through all the details of creating a game and getting it running on most of the major platforms.

OAuth and REST in Android: Part 2

In my last post we went over OAuth in general and we looked at how to use a Java library called Leeloo to authenticate with a service providing an OAuth 2 implementation.

Now that we are able to authenticate a service with OAuth, we need to be able to actually use that service to do something useful.

Many popular web service APIs like Facebook and Twitter provide a REST based implementation.

In this post I’ll show you how to easily connect to one of these web services from Android and parse any responses you get back.

androidrest thumb OAuth and REST in Android: Part 2

Should I use a REST library?

This is a valid question we should address before getting into the details.

My answer to this question is basically “no.”

I first tried the approach of using a REST library to make it easier to communicate to a REST based web service, but quickly found the overhead of the library was more than the benefit it provided.

If you come from a background of calling XML and SOAP based web services, you might be surprised by this answer.  With SOAP based web services it was a huge benefit to use a library to generate a proxy for you to call the web service and let you not have to worry about parsing XML and SOAP headers.

With REST it is completely different.  The whole point of moving to REST based web services is to simplify the process of calling web services.

Most REST based web service interfaces are extremely simple to use.  The idea is that the URL itself contains as much of the data as possible and additional data is included in the POST body.

By adding the complexity of learning a REST library and implementing the proper interfaces required to make it work seamlessly, we can easily add more complexity and overhead than just creating a HTTP request ourselves and parsing the responses.

For this approach I am going to show you how to do just that.

Calling the REST service

In order to call a REST service in Android we are going to first have to discover and understand the REST API provided to us, then make the appropriate calls with the OAuth token we got from authenticating.  Finally, we will parse the result of the call and get back our response.

Discovering the API

Because REST is not really a standard, but rather an ideal, there is not a standard way REST APIs are implemented.

You’ll have to take a look at the documentation for the REST API you want to call to figure out exactly what a call should look like.

In general though a REST API will involve making some kind of HTTP GET, POST, PUT or DELETE request and passing data through the URL or in the request body.

Here is an example of the Dailymile.com API which I have been recently integrating my app to use.

You can see the full API documentation here.

For this API, I am going to show you how I am creating a workout entry using a post.

Making the REST call

In order to make a REST call in Android, we are going to use a HttpClient object and the appropriate http request class.

In this example we are going to use the JSONObject class to create some data in JSON format that we can pass to the REST call by embedding it in the post.

I looked at the API for posting a workout entry to Dailymile, and the format of the request should look like this:

https://api.dailymile.com/entries.json?oauth_token=<token>

The API also indicates that it expects the post body to contain some JSON and gives us a list of required and optional entries that need to be in that JSON object.

Let’s take a look at how I am making this call and then we’ll break it down some.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
	&quot;https://api.dailymile.com/entries.json?oauth_token=&quot; 
    + token);

httpPost.setHeader(&quot;content-type&quot;, &quot;application/json&quot;);
JSONObject data = new JSONObject();

data.put(&quot;message&quot;, dailyMilePost.getMessage());
JSONObject workoutData = new JSONObject();
data.put(&quot;workout&quot;, workoutData);
workoutData.put(&quot;activity_type&quot;, dailyMilePost.getActivityType());
workoutData.put(&quot;completed_at&quot;, dailyMilePost.getCompletedAt());
JSONObject distanceData = new JSONObject();
workoutData.put(&quot;distance&quot;, distanceData);
distanceData.put(&quot;value&quot;, dailyMilePost.getDistanceValue());
distanceData.put(&quot;units&quot;, dailyMilePost.getDistanceUnits());
workoutData.put(&quot;duration&quot;, dailyMilePost.getDurationInSeconds());
workoutData.put(&quot;title&quot;, dailyMilePost.getTitle());
workoutData.put(&quot;felt&quot;, dailyMilePost.getFelt());

StringEntity entity = new StringEntity(data.toString());
httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost);

 

You can see that I am first creating an HttpClient object and an HttpPost object.  The HttpPost has its URL set to the URL for the API call and I am adding a query string parameter to provide the OAuth token we got when when authenticated in my previous post.

I set the content type to be JSON so that we can get back a JSON object from the API call and so it knows that we are passing JSON data.

Then I construct a JSON object in the format specified by the API.  The way to construct the JSON object is to basically create a set of keys and values that are specified by the API you are calling.  In this instance I have a “message” key which I put the message data into. 

The only tricky part is that JSON objects can be nested.  So if you look at the key “workout” in the example above, I am creating a brand new JSON object to use as the value for that key which has its own subkeys which could contain more JSON objects.

Doing it this way is much more simple than trying to construct the string yourself.  The string we end up constructing will look something like this:

{"message":"fun!","workout":{"distance":{"value":5,"units":"miles"},
"activity_type":"running"}}
 
Finally, I put the JSON data into a StringEntity class and set it as the entity on the HTTP Post.  Then we can call execute on the HttpClient to execute the HTTP POST.
 
Handling the response
Now that we have actually made the call to the REST service method we can handle the response by creating another JSONObject from the HttpResponse that is returned.
 
Let’s look at that code and then we can go over what is happening.
 
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseString);
int workoutId = responseJSON.getInt(&quot;id&quot;);

All we are doing in this case is getting the response from the execute call on the HttpClient object, then using EntityUtils.toString to convert the response’s entity to a string representation.  Finally, we construct a new JSONObject from that string.

We can then easily extract any data out of the JSON object by using the methods on that JSON object that let us get typed values out of it.  For this example, I know that I am getting back some JSON that has a key “id” which is the id of the workout I created with my POST.

It is really that simple

The example I am showing you here is one of the more complex examples of calling a REST based API, because we are having to POST and parse JSON data.

In many API calls, you can just use an HTTP GET or a POST without any data to accomplish what you need to in the API.

Some REST based APIs will allow or require data to be passed in a different format, but most of them use JSON notation, which I find the easiest to work with.

Hopefully with these series of posts you can now authenticate against an OAuth 2 based service and make calls to the API to get and manipulate data in Android.

If you have any questions, feel free to drop me a line or post in the comments below.

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out ElegantCode.com where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.

OAuth and REST in Android: Part 1

I recently had the fun experience of learning a bit about both OAuth and making REST web service calls in Android and since I didn’t find much good material out there, I thought I would share it here.

oauthpicture thumb OAuth and REST in Android: Part 1

Let’s talk about OAuth

The first thing you NEED to know about OAuth is that OAuth and OAuth 2.0 are not the same protocol.

From the OAuth guide on hueniverse:

OAuth 2.0 is a completely new protocol and is not backwards compatible with previous versions. However, it retains the overall architecture and approach established by the previous versions, and the same introduction (from the Official Guide to OAuth 1.0) still very much applies.

But, before we get into that, let’s talk a little bit about what OAuth is for.

OAuth basically does two things for a web site providing some kind of service or API that another application might want to use.

  1. It prevents the consuming application from needing to store or have the user’s login and password.
  2. It allows for a scoping of access to the producer’s services.  (For example, a user might be able to login to a site and access all of the features, but an app using OAuth might only be granted permissions to do certain things.)

So now that we know why, let’s talk about how both OAuth and OAuth 2 work from a high level perspective.

From the app developer perspective, the flow goes something like this:

  1. You register your application with the service you want to access and get some unique identifiers for your application.
  2. When you want to access something on the service, you make a request to the service using your unique identifier and telling it where to send the user after they authenticate.  (Usually you would launch a browser window here.)
  3. User will login to the service using the browser window you launched for that service and choose to grant your application certain privileges.
  4. The service will redirect the user to the callback url you provided and include a code you can use to get an access token.
  5. You call the service one more time passing in your unique identifier and the code you got back and the service grants you an access token which you can use to access services you have been granted permissions for.
  6. The next time you need to make a call you can just use that access token instead of going through this whole process again.  (At least till it expires.)

It really isn’t that complicated; the basic idea is that you tell the service who you are and ask the user to authenticate themselves and grant permissions to your application.  Then you prove that you got the response from the server and that it is still you and the service gives you a special pass to access the service.

The real difference between OAuth and OAuth 2 is the protocol itself, not the process.  So this is both good and bad.

Good, because we don’t have to change our process flow and understand something different.

Bad, because we can’t use the same libraries to access an OAuth 2 implementation as we do for an OAuth implementation and vice versa.  There is no backwards compatibility.

For the purpose of this post I am going to show how to use the Leeloo library to connect to an OAuth 2 service.

Connecting to OAuth 2.0

Download the library

The first thing you will want to do is to get the latest version of the Leeloo library.  It has moved to the Apache Amber project, so this link might change, but for now I found the ready to download binaries here.

Configure build path

Once you have the library downloaded you’ll want to add the following jars to your build path:

  • jettison-1.2.jar
  • oauth2-client.jar
  • oauth2-common-0.1.jar
  • slf4j-api.1.6.1.jar

Make initial request for authorization

Make sure you already have a unique client id created with the service you are going to access.  Most services out there like Twitter have a page where you can request one for your application.

Once you have this, you will use this to create a url that you will redirect the user of your application to.

In the code snippet below, I am creating the url and then creating a new Intent in Android that will open a web browser at that url.

OAuthClientRequest request = null;
request = OAuthClientRequest
       .authorizationLocation(authenticationUrl)
	   .setClientId(&quot;&lt;your client id&gt;&quot;).setRedirectURI(&quot;&lt;your redirect url&gt;&quot;)
		.buildQueryMessage();

Intent intent = new Intent(Intent.ACTION_VIEW,
        Uri.parse(request.getLocationUri() + &quot;&amp;response_type=code&quot;));
startActivity(intent);

A couple of things to note about this code snippet:

  • You’ll need to replace client id with your client id and redirect URI with your redirect URI.
  • The redirect URI for an Android application is going to be some protocol that doesn’t really exist, but you can tell your application to respond to.  (We’ll cover that in the next step, but you might have some URI like myapp://oauthresponse)
  • I had to add a “&response_type=code” to the end of my URL because the authentication service required it.  You might have to look and see how the service you are trying to access expects requests to be formed.

Configure your application to respond to your unique URI

In the previous step we had set the redirect to a unique URI like “myapp://oauthresponse”, now you will need to configure the activity you want to handle the response from the service to intercept that protocol.

You can do this by adding an intent filter to that activity like so:

&lt;intent-filter&gt;
	&lt;action android:name=&quot;android.intent.action.VIEW&quot;/&gt;
	&lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;
	&lt;category android:name=&quot;android.intent.category.BROWSABLE&quot;/&gt;
	&lt;data android:scheme=&quot;myapp&quot; android:host=&quot;oauthresponse&quot;/&gt;
&lt;/intent-filter&gt;

With this intent filter we are telling our activity to respond to a URI request in the form of “myapp://oauthresponse”.

Configure your activity to respond to handle the intent you registered to receive

Next we’ll want to set up an override in our activity to handle the new intent that will be called on our activity.  We can then pull the code the service gave us out and use that to request a real token.

@Override
protected void onNewIntent(Intent intent)
{
	Uri uri = intent.getData();

   if (uri != null &amp;&amp; uri.toString()
           .startsWith(&quot;myapp://oauthresponse&quot;))
	{
        String code = uri.getQueryParameter(&quot;code&quot;);
        // ...
   }
}

This code will allow us to respond to the intent that will be fired by the web browser when the service redirects the user to “myapp://oauthresponse.”

Exchange the code for a token

Next we need to get a real token instead of a code.  When the user typed in their username and password and granted access to our application, the server called our callback URI with a code that we extracted in the last step.

Now we can pass that code back up to the server along with our client secret and client id and get an access token.

OAuthClientRequest request = null;

request = OAuthClientRequest.tokenLocation(&quot;&lt;service request URL&gt;&quot;)
	.setGrantType(GrantType.AUTHORIZATION_CODE)
   .setClientId(&quot;&lt;your client id&gt;&quot;)
	.setClientSecret(&quot;&lt;your client secret&gt;&quot;)
	.setRedirectURI(&quot;myapp://oauthresponse&quot;)
	.setCode(code)
	.buildBodyMessage();

OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

OAuthJSONAccessTokenResponse response = oAuthClient.accessToken(request);
String token = response.getAccessToken();

In this bit of code we are sending back to the server all the information we have that identifies our application as well as the code that proves the user allowed us to access that service.

Then we get back an access token from the server.  I would recommend you save this access token so that you don’t have to do this reauthentication in the future.

Wrapping it up

So what we have been able to do here is to redirect a user to the right page to authenticate our application, and then wire up our activity to respond to the redirect the service gives us in order to ultimately get an access token we can use to prove we are authorized to access that service on behalf of the user.

Be cautious though, because not everyone is implementing OAuth 2.0 exactly the same way, since the spec is not finalized.  So you might run into issues where things aren’t working exactly as laid out in this post.  If that is the case, you may have to modify a URL that is generated or something along those lines.

In my next post, I’ll show you what you can actually do with your authorization token.  We’ll go through calling a REST based API web service from Android.

Feel free to post any questions in comments.  I used this code to connect to the Dailymile.com API in my PaceMaker application.

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out ElegantCode.com where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.

Published My First Course on Pluralsight

My number of blog posts in the last couple of months has definitely been a little lower than I like, but I have a pretty good reason.

I just got my first course published on Pluralsight!

logomedium thumb Published My First Course on Pluralsight

The course is called Android Development for .NET Developers and it covers most of the basic knowledge you would need to go from knowing nothing about Android development to being able to create a fairly simple application and publish that application to the Android Market.

If you haven’t checked out Pluralsight, it is a really good site for a wide variety of developer training videos.  They really managed to get some very good content on the site and there are videos on just about every .NET topic you can think of.

I have also really enjoyed working with the guys that run Pluralsight, they are all very friendly and very knowledgeable.  Thanks to David Starr and Fritz Onion for all their help getting my course ready and published.

You never really learn something till you teach it

teacher point thumb Published My First Course on Pluralsight

This simple truth became more apparent to me than ever during the process of making this course.

I thought I had a pretty good understanding of the Android fundamentals, having published a fairly complex application, PaceMaker.

What I became quickly aware of is that there is a huge difference between having knowledge and having understanding.

I equate knowledge as possessing a formula to be able to do something, but lacking knowing why or how to make modifications to the process.

Cooking provides an excellent example of this.  There are many people in the world who know how to cook a large number of dishes.  But many of these people only have the knowledge of cooking.  They have a large collection of recipes which they can follow to produce the desired result.

A professional chef on the other hand, has a true understanding of cooking.  This person might have knowledge of many recipes, but they also understand why the particular ingredients are used and can make modifications to those ingredients and steps.  They may even create something without preset steps because they understand what they are doing, not just have knowledge about it.

It was great to have the experience of creating these videos because I was able to acquire an in-depth understanding of Android development, not just a knowledge of what to do.

If you ever have the opportunity to teach, I definitely recommend you take that opportunity.  Even if you don’t think you are qualified to teach a subject, by the time you have prepared what you are going to teach, you will be qualified.  Trial by fire perhaps, but well worth the outcome.  Plus you’ll be helping others in the process.

Much harder than I thought

I do have to admit though, recording training videos is definitely much harder than I had originally anticipated.

In order to get 40 minutes of video, it might take 6 hours worth of work or even more depending on the prep work involved and how much editing after getting the raw footage.

I really expected that it would take about as much time as it takes to record something to produce that something, but I definitely learned that is not the case.

I often found that I had to draw a line and stop trying to refine a video because you can literally spend an unlimited amount of time editing and tweaking a video.

Another revelation that might be apparent to everyone else, but was quite an epiphany to me was that you can edit “umms” out of video very easily.  You can’t even notice where they are cut out!  My first video, I didn’t even realize I could edit anything, and I ended up taking like 50 cuts until I could get it right.

Overall though, great experience, lots of fun

I felt like I’ve been stretched in a different direction, as I had never done any video or audio recording before and had never really spent much time in a room talking to myself pretending to talk to other people, but it was a good kind of stretching.

I really actually enjoyed the process and I will definitely be doing more of this kind of work in the future.  Probably going to take a bit of a break before I start my next course though.  I want to make sure I take some time to get a good retrospective of the process and sharpen my saw a bit so my next videos can be even better.

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out ElegantCode.com where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.

Book Review: Pro Android 2

I recently completed reading Pro Android 2. It is a pretty large book, so it took me awhile, but I finally got through it. I hadn’t really read any other Android books, so I don’t know how it compares.

proandroid2 thumb Book Review: Pro Android 2

The book goes through creating an Android application using Eclipse. It contains many source code examples that are very complete. The book really seems to be focused more on getting going vs going in-depth with the APIs.

The good:

  • Great jump start diving right into Android development without wasting much time.
  • Very complete examples that can get you going and can be modified for your own application.
  • Balances basic examples with more complex architectural constructs well. There is a good mix of examples that build on basic concepts and show how to implement more of an MVP style of development.
  • Covers a pretty wide breadth of the Android platform, which makes it easy to know what exactly is capable.

The bad:

  • Although the beginning of the book was very interesting and informative, some of the chapters seemed to drag on.
  • A whole huge chapter devoted to search.  Search is not something that most applications would need to make use of.
  • A whole huge chapter on 3d application development.  Not something I felt should have been in the book.  Pretty boring and actually really scary.  I don’t think I’ll ever develop a 3d application for Android.

What I learned:

I had already started building my Android application before reading this book, so not very much of it was completely new to me, but I definitely learned some things from the book.

I was really surprised to see how easy 2D animation is with Android.  The book does a good job of explaining it and providing examples.  I feel like I could very easily implement 2D animation after reading this book.

I learned about how to create and use content providers.  This aspect of Android development is a bit tricky, but I felt like Pro Android 2 did a good job of explaining it and providing examples that I would be able to use.

I also learned to create a home screen widget.  The examples in the book were really good and provided a complete usable implementation that could be easily used as a base for creating your own.

Towards the end of the book, Titanium Mobile is mentioned.  Titanium Mobile is a WebKit-based native application development framework which allows developers to write applications that target multiple platforms.  It looks really cool, and I kind of wish that was the first chapter in the book so that I could have explored that before getting so far into actual Android development.

Overall, I would definitely recommend the book.  I feel pretty confident that someone with no Android experience should be able to pick up that book and get going with their first application.  I definitely learned some things the hard way before I read the book.

Android Presenter To Activity Using Guice

In a prior post I talked about how to unit test android applications.  I made some references to wiring up an Activity with a presenter, but I didn’t really show how I was doing that.

I got some requests to show some sample code, so I thought I would explain what I was doing here and see if anyone had better suggestions.

Roboguice

To make it easier to unit test and to decouple my system as much as possible, I am using a dependency injection framework called Roboguice.  It is basically the Google Guice framework that is ported to Android and adds some Android specific functionality.

One challenge you will most likely first encounter when working with Roboguice is that a presenter is going to need a reference to the Activity class that is going to represent its view.  Since the Activity class has to create the presenter, this presents a dependency injection challenge.

We can’t just ask for a presenter from our container and have it auto-resolve the dependency on the Activity.  (That is we can’t rely on constructor injection in this case.)

Setter injection to the rescue

One thing we can do, is use setter injection instead of constructor injection to inject the other references our presenter will need.

Guice provides us with an easy way to perform setter injection after we have created the object.  I use this technique to make sure that I can pass my activity into the presenter and still have the benefits of having the other dependencies injected into the presenter.

Here is some code showing my OnCreate method inside my activity.

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.pacemaker);

    this.presenter = new MainPresenter(this);
    Injector injector = Guice.createInjector(new PaceMakerModule());
    injector.injectMembers(presenter);
}

This code is creating an instance of my presenter which holds a reference to the Activity, or view, it is manipulating.  Then Guice injects dependencies using the module I created into any properties that are annotated with @Inject.

Here is what some of those presenter set methods look like:

@Inject
public void setSystemClock(ISystemClock systemClock)
{
     this.systemClock = systemClock;
}

@Inject
public void setRunSerializer(IRunSerializer serializer)
{
     this.runSerializer = serializer;
}

You can see that they are declared in the module like so:

public class PaceMakerModule extends AbstractAndroidModule
{
   @Override
   protected void configure()
   {
	bind(ISystemClock.class).to(SystemClockWrapper.class);
	bind(IRunSerializer.class).to(GPXRunSerializer.class);
    }

}

It’s not exactly pretty, but Android applications are really a loosely coupled sets of Activities which are the entry point into your code.  It makes it very difficult to create a MVP type of framework that we might be used to.

If you know of a better way than what I am doing please let me know, and if you have any questions or suggestions, I’m always glad to hear them or help if I can.

The Best Way to Unit Test in Android: Part 2

In my last post I presented two choices for unit testing in Android.

  • Unit test on the real device or emulator using the real android framework
  • Unit test on our PC using the JVM

Each choice has some pros and cons, but for me it came down to the speed and flexibility allowed by running in a real JVM.  I actually tried to create an Android unit testing project using the scaffolding provided by Google but it turned out to be very restrictive, especially since I couldn’t use JMock.

There is also something to be said for being able to execute the unit tests extremely quickly.  If you have to wait for an emulator to come up, or try to run them on a real device, it is less likely the unit tests will be run.

How to do it

The basic idea of this approach is fairly simple.

We are going to try and abstract away any Android specific calls from our application and then unit test the plain Java logic in the application just like we would any other Java project.

Step 1:  Create a JUnit project

Create a new JUnit project just like you would for unit testing any Java application.

newjavaproject thumb The Best Way to Unit Test in Android: Part 2

Make sure you chose Java Project rather than Android Test Project.

From here you can add your JUnit references to your build path.  I would also recommend adding Instinct for doing BDD style testing.  Instinct uses JMock internally to create mocks for you using a declarative approach.

The only other thing you will want to do with this project is to add the android.jar to the build path.  The android.jar can be found in your Android SDK directory under the platform directory that corresponds to the API version you are targeting with your application.

For example, on my machine, I am targeting Android 1.6, so my android.jar is at:  C:\Android\android-sdk-windows\platforms\android-4.

Now remember, you are including the android.jar in the project only so your classes can understand what types exist in the Android framework.  If you even try to call a constructor on a class in android.jar, you will get an exception.

Step 2: Pull all the code you can out of the Activity.

The next thing we need to do is clean up our Activity class to make sure that it has the smallest amount of logic in it as possible.

Since we can’t actually instantiate any types that exist in the Android framework, we are not going to be able to create an instance of our Activity in the test project.  So we are not going to be able to unit test our Activity.  This isn’t a problem if most of the logic we care about testing exists in other layers in our system.

You can design the lower layers however you want.  I am still not quite sure the best approach here, but what I did was put a presentation layer directly below the Activity.  I have a Presenter class directly below the Activity that tells my activity what to do.  The Activity passes on any interesting events or information to the Presenter.

You should leave the Activity with the responsibility of setting the text on its own view objects, but create methods for your lower layers to tell the Activity what text to set the objects to and so forth.  Activity is going to act as an adapter to a large portion of the Android framework for your application.

Because the entrance point into your application is going to be the Activity, you will need to wire up the rest of your layers from the Activity.  This is a little strange, but it works.  In my application, I create a new Presenter and pass this into it on the constructor.

When you are done, your Activity should look pretty thin.  It should delegate all its event handler logic down to the lower layers and act as a pass through for manipulating the view.

Step 3: Wrap remaining Android object calls.

You’re going to find that some of the remaining Android API will need to be called from lower down than the Activity.  This is not as big of a problem as it seems.

In my application I needed to make some calls to android.os.SystemClock.  I needed to make those calls lower down than the activity because it is part of the heart of the logic of my application.

I created a simple SystemClockWrapper class that wraps system clock and delegates any calls to the real SystemClock class.  Then I extracted an interface from that class called ISystemClock (hey, I like the C# convention for interfaces.)

Finally, in my application logic, I allowed the ISystemClock reference to be passed in or “injected” through the constructor of the class that used it.

public class SystemClockWrapper implements ISystemClock
{
     public long getElapsedRealTime()
     {
          return SystemClock.elapsedRealtime();
     }

}

public interface ISystemClock
{
     public abstract long getElapsedRealTime();

}

In my unit test I just pass in a mock version of the ISystemClock interface.

One hint here is to use the refactor tool in your IDE to extract an interface.  This can save you some time of trying to manually create interfaces for large pieces of functionality you are wrapping.

Putting it all together

Now you should be able to create your unit tests against most of your application logic and run them just like any other unit test project.

The only thing you won’t be able to do is unit test the logic in your Activity classes.  This shouldn’t be much of a problem if you have made them into views, because they should only contain view logic.

If you really want to be able to write some tests for the Activity though, you can create another actual Android Test Project and use Google’s framework to write unit tests from there.

The Best Way to Unit Test in Android: Part 1

I’ve been doing some development in Android lately on a top secret project, one that hopefully will change the way you run with your phone.

In the course of building this app, in a previous post I mentioned that I wanted to find the right, or perfect way, to build an Android application.

I haven’t found the best way to build an Android application into a nice clean design pattern, but have found a way that seems to work, and makes the application testable and easy to maintain.

I do believe though, that I have found the optimal way to unit test in Android right now.  Yes, a bold statement, but I have looked high and low for a better solution, and can’t find one.

htcandroid thumb The Best Way to Unit Test in Android: Part 1

The problems

So first a little bit of background on the problem with unit testing in Android.  Take what I say with a grain of salt here, because I am not an Android platform expert, and feel free to correct me if I misstate something.

Android.jar

If you download the Android SDK from google, you will find that the android.jar you get with the SDK is much like a C++ header file; it doesn’t actually contain any working code.  As a matter of fact, all the methods are stubbed out to throw an exception with the message “Stub!” when you call them.  How cute.

The real android.jar implementations live on the emulator, or your real Android device.  So, if you want to actually run any code that is going to call any methods or try to construct real Android framework classes, you must run that code inside the emulator or a real device.

Dalvik VM

When you’re working with Android, it sure feels like you are writing regular old standard Java SE code, but you are not. You probably won’t notice the difference, as almost everything that you need is there in the Dalvik VM implementation of Java.

Dalvik is not even a Java Virtual Machine at all.  That is right, it runs on cross-complied .class files which are converted to a .dex format.  Yes, it does not use java byte code.

Why do I mention all this?  Because you might want to use something like JMock to mock your dependencies when writing your unit tests.

Well, you can’t.  It just isn’t going to work, because the Dalvik VM doesn’t use java byte code, so the reflective coolness that mocking frameworks like JMock use doesn’t work the same.

Be aware that any external library you try to use in your Android project may not work because Android does not support the full Java SE implementation.  It actually is a subset of the Apache Harmony Java implementation.

There is no main()

Where does an Android application start running?  From the activity.  Which is basically the view.  (Some people will argue this is the controller or presenter.  And yes, I agree in respect to the Android framework it is, but in regard to your application framework it is the view.)

Android applications define a starting activity and launch from there.  Activities can even be launched from other applications.

This tends to disrupt most of our MVC, MVP, MVVP pattern architectures, as the view is going to be the entry point and will have to be responsible for initializing the rest of the application.  (That is not entirely true, as there is an android.app.Application class that gets called the first time your app is run, to launch the main activity, but for the most part you can’t do much here.)

Essentially though, you have to build your architecture based on each Activity being its own separate little application, with the entry point being in the activity.  This puts some serious constraints on unit testing.

Putting it all together

So if I can sum up the problems briefly, I would say:

  • Android framework code has to run in the emulator or on a device.
  • Dalvik VM doesn’t allow us to use our standard mocking frameworks.
  • Entry points for our applications are in the views.

The first problem, combined with the second, lead us to an interesting choice.  Should we run our unit tests on an actual emulator or device using the Dalvik VM, or should we run them in a JVM?

It is probably not an obvious question, but let me explain why it is the most relevant.

In writing an application, we are going to have application logic that has nothing specifically to do with the Android platform, and we are going to have Android platform specific logic (drawing views, handling Android OS events, interacting with Android APIs etc.)

If we want to write true unit tests, we need to isolate our classes and test them individually.  We should be able to do this for our application logic, without relying on the Android framework.  If we don’t rely on the Android framework, we don’t need to run on a real or emulated device, thus we are not constrained to the Dalvik VM.

If we choose to run our unit test code on a real or emulated device:

  • We will be able to use the Android framework APIs in our testing efforts.  For example, we can create new location objects instead of mocking them up.
  • We will be completely true to the real execution of our code since we will be using the real VM the code will run on.
  • Since we are running our tests on a device or emulator, they will run much slower.
  • We won’t be able to use JMock, EasyMock, or Mockito, we’ll either have to roll our own mocks or use a fledgling Android mocking framework.

If we chose to run our unit test code in a JVM on our PC:

  • We will have the full power of the JVM available to our test code, so we can use mocking frameworks like JMock, and BDD frameworks like Instinct.
  • We will run our unit tests much faster, since they will be using our PC instead of a device.
  • We can use standard unit testing practices and not have to inherit from special Android classes, or use special Android test runners.
  • We will have to wrap any calls to the actual Android framework if we need to use any Android classes or services deeper down in our application.
  • We have a small risk of having different behavior between running the tests and the real application because we will be running the code on different VMs.

In my next post, I’ll detail which option I chose and why and also give some detailed steps of how to get setup and running.

C# vs Java Part 2: Desktop and Mobile Platforms

In this post we’ll be looking at both the desktop and mobile platforms for C# and Java.

The Desktop (Thick Client Applications)

The desktop platform, or thick client, is not as important of a platform as it was several years ago, and it seems to be getting less and less important everyday.  Although, like a pendulum, development seems to swing back and forth between thin and think client experiences.  It seems as though the current trend is thick client functionality in a thin client package.  (The browser as the OS).  For this post I will assume the development of a true thick client application, which is one that runs natively on the client computer and is installed or executed from the client computer.  (Although, as I am making this statement I am realizing even that line is becoming blurred with Adobe Air and Silverlight.)

Java

There isn’t much choice here.  Really, it comes to two options.  Swing or SWT.  I’ll confess my ignorance here.  The only thing I really know about Swing is that a long time ago I wrote an application that bounced an image around the screen using a second thread.  I tried to do a bit of research here, but I am not coming up with a large amount of information.  Probably because not many people are actually doing thick client development in Java anymore.  I asked one of the best Java developers I know, (Sreenivasa Majji), and he was able to give me some information.

Apparently, Swing has gotten much faster and easier to use since last time I used it.  From my understanding, Swing is pretty comparable to the previous generation of .NET thick client frameworks, Windows Forms.  SWT also seems to have comparable functionality, including data binding.  The real advantage that Java has here though, is the multi-platform capabilities.  A Java desktop application can be run on any operating system that supports Java.  (Which is pretty much any operating system.)  Deployment has always been an issue in thick client applications, and Java Web Start tends to solve that problem by allowing a client to visit a web page to launch the application.

I have heard complaints that not much progress is being made on Swing or SWT, which seems like it is true.  I know finding information about the technologies is not very easy.

C#

The current generation of C# thick client applications use WPF.  WPF is basically a wrapper around the DirectX libraries which uses XAML, (an XML based scaled vector graphics UI convention), to create the user interface.  WPF development is different from Windows Forms development in many ways.  WPF development separates the UI from the logic behind the UI very clearly.  XAML is used to define the layout and elements that exist.  The UI can almost be completely independently developed by a designer.  Everything in the UI is completely customizable, any control can be drawn from a vector representation replacing the default version of that control.  Animations and 3D graphics are easily achieved since WPF is built upon DirectX instead of the Win32 libraries.  The UI is also scalable since everything is represented in vector graphics.

Desktop development with C# using WPF is very nice.  I haven’t done a large amount of WPF development myself, but what I have done has been pretty easy and straightforward.  The power to use any SVG image or animation can make for some pretty nice UIs.  It can also make for some pretty inconsistent UIs though.  One major advantage that I see for WPF is that it uses XAML, which is the same technology that Silverlight uses.  I know that Silverlight and WPF are not 100% compatible at this point, but they do share many commonalities.  I have heard of a few frameworks that try to abstract their difference, but I don’t know of one that does that really well yet.  I am sure one will be developed, or Microsoft will provide a solution in the near future to make it possible to build an application that can easily be run as a WPF or Silverlight application.

Conclusion

In this case, I think it depends where your install base is.  If you are targeting a Windows user base, I think it would be pretty difficult to come up with a reason to use Java over C# for desktop development.  If you are targeting a multi-os install base, C# could be used to do Windows Forms application development using Mono, but Mono doesn’t support WPF.  Java is the most logical choice for doing a multi-platform install if you have to use a thick client.  I especially would not want to try and troubleshoot a bug that is different in Mono vs the .NET CLR.  I tend to see most traditional desktop applications being replaced with Rich Internet Application (RIA) technologies like Adobe Air, Silverlight and JavaFX.  One other side note here; Java and C# are able to call into unmanaged libraries (or native code), using P/invoke for C# and JNI for Java.  If you need to do that, C# P/invoke is by far easier than JNI, especially with the dynamic keyword being added to C# 4.0.

Mobile

Welcome to the next battleground.  This platform is under heavy turmoil right now.  Microsoft is being killed here by Apple and Google, both producing by far better user experiences.  Unlike the other platforms, the choice of language and technology here is more driven by adoption than by convenience.  What I mean by that is that there is almost no point deciding what technology to use based on language or features, it is more based on what kind of device you want to target, and who is winning the mobile device war.  Now, this is not entirely true, since there are ways to develop in C# on the iPhone ,as well as, Android platforms.

Java

When talking about Java mobile development there are two branches, Java ME, and Android development.  You can disagree with me if you want, but as far as I am concerned Java ME on mobile devices is pretty much dead or dying.  The idea, however, is great.  Multi-platform development on the widest landscape, mobile phones.  But, the user experience was pretty much horrible.  I have had several mobile phones running different OS versions and each one that had Java on it had some applications that weren’t really that great and didn’t integrate into the phone well.  Apple blocked Java out of the iPhone anyway, which is a huge market sector.

So, let’s talk about Android.  Android is awesome.  I love the idea, the technology is great, it is constantly improving and the architecture is wonderful.  Good job Google, you have made an easy to develop for platform that Java developers will be able to quickly adapt to and use to write rich mobile applications.  Android development is basically writing Java code, which gets converted to a specialized JVM that sits on top of a Linux kernel and some graphics APIs.  Applications use a provider model, which allows mashups of different applications as one application’s requests can be fulfilled by part of another application.  The development environment takes minutes to set up if you use Eclipse.  The UI is nicely separated from the code through the use of layouts and resources.  My only real complaint at this point is that you currently have to look up resources by an ID then cast the resource to the appropriate type.  The build is already using code generation to create a R.java file which holds the references to all the resources.  I cannot understand why Google didn’t make that code generation generate strongly typed methods for each resource.  Perhaps I am a fanboy of Android, but I have to say, I like it and I think it is the future King in the mobile market.

C#

Do you know how easy it is to create a Windows Mobile application in C#?  It is so easy that if I gave you Visual Studio and 5 minutes, you could probably figure out how to make “Hello World” appear on the Windows Mobile emulator.  Really, it is that easy.  It’s a shame that the current version of Windows Mobile is so lacking.  Now, don’t get me wrong.  Windows Mobile is powerful.  It is amazing what you can do with Windows Mobile so easily, since you have the power of almost the entire .NET framework at your fingertips.  It is a well designed OS, it runs applications really well, it transfers the Windows look and feel we are all so familiar with to a mobile device very well.  But, that is exactly what the problem is.  It is not really an OS designed for a mobile phone.  At least not the way people really want to use their mobile phone.

So, let’s talk about the development environment for Windows Mobile using C#.  It is almost exactly like developing Windows Forms applications.  It’s incredibly easy, and for the most part, you don’t even realize you are developing for a mobile phone.  The emulator is built right into Visual Studio, you just hit run and it launches the emulator and your application.  The .NET compact framework has fewer features than the full .NET framework, but most of it is there.  One difficulty though is trying to get into the core services of the phone.  It is not very easy.  For example, trying to replace the dialer application is not really possible.

Silverlight mobile may save the day for C# development on mobile devices, if Microsoft can manage to bring it to iPhone and Android, but for now it’s unknown.  Also, the next generation of Windows Mobile devices using Windows Mobile 7 may change the game for Microsoft, but with it’s Q4 2010 release date, I fear that it will be dead on arrival.

Conclusion

Mobile development is kind of like the wild west right now.  It’s a huge risk to settle into a technology platform.  I place my bets on Java and Android, because it seems to me like the best combination of a good operating system and good development environment.  I didn’t really mention this, but iPhone development using objective C is ridiculously complicated and makes me want to smash my head into the wall.  Having done both Windows Mobile and Android development, I would say Windows Mobile development is slightly easier, but they are pretty comparable.  The reason I would choose Java and Android despite this is because Android is a better platform, a growing market, and has a delivery mechanism to easily sell your applications.

Final words

Comparing C# and Java development platforms is very difficult due to the overwhelming amount of information out there about each platform and language, but I have tried to take a fair and honest approach.  It is pretty clear that each language and corresponding technology have advantages and disadvantages for each platform.  I can’t pick a clear winner from the platform perspective, like I could with the languages.  In the next part I will talk about the non-platform specific frameworks that Java and C# have to work with.

C# vs Java Part 2: The Platforms (Web)

C# vs Java Part 1: The Languages (Continued)

C# vs Java Part 1: The Languages