How I built an Android app in C# & Visual Studio in less than 24hrs


Yes you read that right! – I built an android app with the tools that I know – Visual Studio and in my favorite language C#. Well that’s possible because of Xamarin. In case you didn’t know – Xamarin was founded by nice engineers(Nat Friedman & Miguel de Icaza of Mono fame) who built MonoTouch and Mono for Android which are cross-platform implementations of Common Language Infrastructure (CLI) and Common Language Specifications.

I love C# and it has been the language that I have been associated with all my developer life. So when I thought of developing an app for mobile, I wanted to use the tools that I know rather than go learn something new! Being a C# developer it is quite obvious for me to choose Windows Phone or Windows 8 as the mobile platform to launch my app. But wait a minute, I want them to be built on other shiny platforms too – Who’s gonna build the same app for the famous Android and iOS ? Well I want my app to be used by a million users, if not more! HTML5 based hybrid apps are an option but arguably they aren’t the best fit when it comes to User Experience – at least at the time of writing this post.

Forget all that! – I don’t even want to write HTML5 and JavaScript, I want C#. Yeah!!

Xamarin – Why I love it!

Xamarin let’s you create apps in C# for iOS, Android & Mac. Period.

I had a compelling reason (which I am gonna share with you later) to go write a native android app. So I decided to give Xamarin a try – downloaded the trial version and gave it a shot. And the result – a simple app called TripXpense built in less than 24hrs with no knowledge on Android platform or the way it works! Though it’s a simple app, it would have taken me weeks if I had to build it on Java. Most importantly Xamarin let’s me write in Visual Studio with my favorite plugin resharper running on it. What more can I ask?

Xamarin’s Android API exposes almost 100% of the Andriod’s – that  said you can build a complete android app in C#. I must mention this – Xamarin documentation is a piece of great work from their talented team! They are brilliant!! Honestly, I haven’t even visited the Android SDK Documentation for help.

So what’s the app?

Well it’s TripXpense – a simple app that let’s you add Trips and Expenses. There are only 4 screens and there’s nothing shiny in this app yet because you know it – It’s been just 24hours of the code. If you think you can do better – go fork it from GitHub.

2

Disclaimer: I am just sharing my experience of an Android Development on this new amazing platform that I love. That said this is no expert material.  Refer Xamarin & Android documentation for patterns and right way of doing things. The code works on my PC & comes with no warranty.

Few Android related stuff that you should know!

Project Structure:

image

This is how a project structure of an Android app will look. When you create a new Android application in Visual Studio, Xamarin set’s it up for you by default.

Few things to make a note of – only a few for now.

AndroidManifest.xml

Every Android project must contain this file. The manifest lets you define the metadata of your application like Application Name, Package Name, Required Permissions, Activities etc. This is similar to a App.config or Web.Config files but differs in certain ways. In Xamarin you can easily edit manifest information by going to the properties of the project. Please note that there are other values that are auto generated by Xamarin from the attributes that you define in classes. You can learn more about it from the documentation.

Resources

It’s a good practice to keep non-code resources like images, icons, and constants external to your code. Android expects you to store them in a specific sub folders within the resources folder. Notice 6 different Drawable folders which are kept separated based on the DPI displays. These folder will include respective sized bitmaps & PNG images. Perhaps the most powerful Resource to be noted is the Layouts.

Layouts

Layout is the User Interface – Yes that’s right! Whatever user sees is what is designed inside layout files. These are xml based and have the extension .axml . It decouples the presentation layer – much similar to XAML in Windows Phone.

Here’s an example of a layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/MyButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Hello" />
</LinearLayout>

Activity

Activity is the class responsible for setting the UI content for the users to interact! You can consider this as a code-behind for the Layout written in the resources. So the activity class will contain the presentation logic of your view. It is the class that is referenced by the Android system to do the user interaction. Activities are created or destroyed by the Android system. It’s important to understand the Activity Life Cycle to effectively handle user data in the changing states such as Running, Paused, Backgrounded  & Stopped. For the TripXpense app, I am yet to implement this feature. Here’s an example of an Activity.

namespace HelloXamarin.Android
{
    [Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

           // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
        }
    }
}

All your Activity classes should derive from Activity base class. Notice the MainLauncher = true set in custom attribute – this is to set the starting screen of your app!
OnCreate() is called when the activity is created. It’s always overridden to perform startup initializations such as

  • Creating  Views
  • Initializing variables
  • Binding static data to lists

Notice the SetContentView() – It places your layout on the screen. Layouts can be accessed using the static variable Resources.Layout.<yourLayoutName>.

Now let’s add a Click event handler to the button placed in the Layout. Shall we?

To get the reference of the button placed in the layout use the helper method FindByViewId<T>() and pass the Id of the button you set in the resource. Once you get the handle – just add the event to the Click handler.

[Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private int count = 0;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

           // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }
    }

To navigate to another screen and pass some extra information along, use StartActivity() with an intent that contains the extra information. Extra information is nothing but the data that you want to pass between your screens.

          button.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(DetailActivity));
                    intent.PutExtra("userCount", count++);
                    base.StartActivity(intent);
                };

Finally to receive the extra information that was passed from the previous screen you can use Intent.GetStringExtra or other type based methods. Here’s the full code:

    [Activity(Label = "DetailActivity")]
    public class DetailActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Detail);

            var t = FindViewById<TextView>(Resource.Id.textView1);
            t.Text = string.Format("{0}:{1}","You clicked ",Intent.GetIntExtra("userCount", 0));
        }
    }

Now let’s look at the TripXpense app and few fundamentals of the Xamarin app Development.

TripXpense – built using Xamarin!

tripXpense

TripXpense has 4 screens

  1. Home Screen – that shows list of trips and you can add more
  2. Trip Edit Screen – add and edit trips
  3. Trip Details Screen – displays trip summary and Expenses
  4. Expenses edit screen – add and edit expenses
Cross-Platform development

Xamarin supports cross-platform development in C# but it is not just a write once and run everywhere platform. Because one of its strengths is the ability to implement native user interfaces specifically for each platform. So when you architect your apps make sure you separate the code that is shareable across platforms. Refer Building Cross Platform applications.

Separate reusable code into a core library:

For this app I decided to have my database as xml and created all my classes related to business logic, repository and data access in the core library called TripXpense.Core.  In case I decide to build a Windows Phone, Windows 8 or an iOS app in future, these files don’t have to be duplicated.  And they can be unit tested too! Here’s how it looks:

image

Please note – You cannot reference this library directly as it is not targeted to Android. And you don’t want to do so because you want them to be accessed by other platforms. Instead you need to use Project Linker extension for Visual Studio which will ensure you have the same code in your Android project. Refer Visual Studio Project Setup Walkthrough

Create an Android Project in the same solution and link the Core project using Project linker. Here’s how your Android project will look with a small blue icon below :

image

Finally I created the Screens and necessary layouts in Resources and made my app come alive.

Code on Github

You can download this app from my GitHub repository.  Go play around with it and let me know what you think!

Have any questions? Find me on twitter – @nishanil

Advertisements

15 thoughts on “How I built an Android app in C# & Visual Studio in less than 24hrs

  1. I have developed in java and c++ for 10 plus years. I always stayed away from C#, due to it having the stigma of a scripting language, and I made the mistake of equating it to javascript.

    I will say, I’ve developed several projects in c# in the last year and with a lot more ease than with Java. I’m not constantly writing, adding, and rewriting library files.

  2. hai! how can i download and install xamarin studio in my 64bit windows8 pc.plz help me to do this.Don’t send link,tell me procedure also………..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s