Migrating Android Applications to Windows Phone 7

Share this article

This article gives you a hands on approach to migrating an application written in Java using Eclipse for Android, to Windows Phone 7 using Visual Studio, C# and Silverlight. You’ll take a look at a complete Android application, and see how to migrate its user interface and code over to Windows Phone 7. You’ll see how you can use the Interoperability Bridge from Microsoft to assist in API translation.

The Android StckPckr Application

The application is a fun little tool that takes a look at stock price history and uses technical analytics on a stock to determine if now is a good time to buy it, or a good time to sell it. Please note that this is just a demonstration, and you should not base your investment decisions upon it.

It takes a look at the stock price history over the last 2 months, and calculates what are called ‘Bollinger Bands’ for the stock. These provide an indicator for the statistically relevant values for the stock. An indicator that it might be a good opportunity to buy the stock, because its price is relatively low, comes when the stock is at the bottom of the bands. Similarly if its price is relatively high, it will be at the top of the band.

The app will allow you to type in a stock ticker, and calculate the band. It will then convert the current price of the stock into a position within that band, with 0 being at the bottom and 100 at the top. It will use this to drive a slider in the UI to show you the relative position of the price.

So, for example, Figure 1 shows the calculation for AAPL on November 14, 2011, running in the Android 2.3.3 Virtual device. It bases its calculation on the closing price of the day before. For Apple, this was $384.62. Today, as I run the application, the stock is trading for $379.77, showing that the methodology is quite accurate!

1 Android StckPckr App

This application is a good, simple, example of an application to port because it:

  1. Has an XML-defined user interface, within Main.xml.
  2. Uses code to initialize some parts of the UI, for example, defaulting the status slider to ‘50’, as well as using code to dynamically update the UI, changing the value of the slider once the analytic is complete.
  3. Uses the network stack to consume information over the internet, and requires the manifest to provide permissions to allow this.
  4. Uses pure Java for the math involved in calculating the data.

Regardless of what your app is or does, most apps will have some of each of these pieces of functionality, so, if you can port this app, you are well on the way to being able to port any app!

Getting Started with Windows Phone

At this point, I’ll assume that you already have Eclipse, the Android SDKs and everything else you need for Android development. If you don’t, please go visit the Android Developer portal and get yourself set up. We’ll be looking at Eclipse with the StckPckr application a little later on.

For Windows Phone development, you can use Visual Studio Professional, if you already have it, or, if not, the free Visual Studio 2010 Express for Windows Phone does the job nicely. You can download this from Microsoft using the link.

There aren’t a lot of major differences between the free and professional versions of Visual Studio if you are just getting started, so don’t worry if you just want to use the free one. The main difference you may see when following through this article when using Visual Studio Express is that there are less application templates available to you.

To get started, once you’ve installed Visual Studio, launch it, and from the File Menu, select ‘New Project’. You should see the list of template types. Select ‘Silverlight for Windows Phone’ on the left and ‘Windows Phone Application’ from the list of available types of available types. See Figure 2.

2 Launch Windows Phone App

Give your application the name ‘StckPckr7’ and press OK. Pick Windows Phone 7.1 as your target OS and press OK.

Visual Studio will create a new Windows Phone 7 project for you and load the user interface into the designer. It will give you the visual representation of your UI and the XML markup defining it side by side. Microsoft calls UI XML Markup ‘XAML’, which stands for XML Application Markup Language. See Figure 3.

3 Visual Studio Designing UI

As an Android developer using Eclipse, you’ll be used to having to configure multiple AVM’s based on the different OS or device types that you target, from Android 2.1 phones all the way up to Android 4.0 tablets. As there is relatively little variance in Windows phones, the emulation experience doesn’t require such configuration. Simply press the Run button (or F5) to launch your app within the emulator as you can see in Figure 4.

4 Windows Phone Emulator

Great, now you have everything you need to get started. So let’s switch back to Eclipse and take a look at the Android application.

Porting the Android UI to XAML

The best place to start will be with the XML that defines the UI for the StckPckr application, and migrating that over to XAML. In Eclipse, within your app/res/layout folder, you’ll see a file called ‘Main.xml’. Open it up and you’ll probably see it in the visual designer, like Figure 5.

5 StckPckr UI Android Eclipse

I find the Outline view, to the right in this diagram to be particularly useful. It shows the class of each control in this UI, which as you can see in this case, is:

  • LinearLayout
    • textView1 – ‘Welcome to StckPckr’
    • linearLayout1
      • textView2 – ‘Enter Ticker’
      • editText1
      • button1 – ‘Go’
    • SeekBar1
    • textView3 – ‘ – Buy Sell- ‘

The first LinearLayout is the root of the view, and it contains 4 controls: The TextView that says ‘Welcome to StckPckr’; a LinearLayout control which contains a number of controls in its own right; a seek bar; and another text view. These controls are laid out vertically.

The LinearLayout called ‘linearLayout1’ is a child of the first, but it is oriented horizontal, and it contains a TextView, an EditText field and a Button.

Each of these controls has a corresponding control in Windows Phone 7, and a great way to find out what they are is to use the API Mapping Tool provided by Microsoft.
So, for example, look up the LinearLayout control using the API mapping tool. It will map you to something called a ‘StackPanel’, and if you look up its HORIZONTAL and VERTICAL enumerations, you’ll see that they correspond to an enumeration in Windows Phone 7 called ‘Orientation’. Similarly, you can see the following mappings:

  • Button -> Button
  • EditText -> TextBox
  • SeekBar -> Slider

The TextView is missing from the current incarnation of the API mapper, but in Windows Parlance it is called a TextBlock. So a rough translation of your UI should look like:

  • StackPanel (Orientation=”Vertical”)
    • TextBlock – ‘Welcome to StckPckr7’
    • StackPanel (Orientation=”Horizontal”)
      • TextBlock – ‘Enter Ticker’
      • TextBox
      • Button – ‘Go’
    • TextBlock – ‘ – Buy Sell – ‘

With a little searching you can find some other goodies too. For example, text alignment is done in Android using ‘gravity’, and you can see that the TextView control, for example, uses it like this:

    android:text="Welcome to StckPckr"
    android:textAppearance="?android:attr/textAppearanceLarge" />

A quick search of the API mapper shows that for many Android controls Gravity maps to Alignment. A neat part of intellisense in Visual Studio isn’t that it is triggered by matching the characters you type to the first part of the property – it instead does it to any part of the property. So, if, for example, you are editing a TextBlock, and you type ‘Align’, you’ll see ‘TextAlignment’ shows up as an available property, and this is what you’ll use to do centering of text the way gravity does it in Android.

Editing your XAML

The XAML Editor in Visual Studio is very friendly, and provides intellisense and autocomplete to help you fill out your tags. Take a look at it in Visual Studio, and your MainPage.xaml will look something like this:

    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid Name="LayoutRoot" Background="Transparent">
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

    <!--ContentPanel - place additional content here-->
    <Grid Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>

<!--Sample code showing usage of ApplicationBar-->
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
            <shell:ApplicationBarMenuItem Text="MenuItem 2"/>


The highlighted part is where you will draw your UI. The rest is the UI that is provided for you by the OS, but you should edit the TextBlock controls that specify ‘My Application’ and ‘page name’ to something a little friendlier.

Now, within your Content area, the grid called ContentPanel, you can define the UI as you figured out above. As you type out the tags, intellisense helps you out, and makes it easy to find the right properties. It should look something like this:

<Grid Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <StackPanel Orientation="Vertical">
        <TextBlock Text="Welcome to StckPckr7 for Windows Phone"></TextBlock>
        <StackPanel Orientation="Horizontal" Margin="0,20,0,0">
            <TextBlock Text="Enter a Ticker"></TextBlock>
            <TextBox Text="" Width="200"></TextBox>
            <Button Content="Go"></Button>
        <Slider Maximum="100" Value="50" Margin="0,20,0,0"></Slider>
        <TextBlock Text=" -- Buy    Sell --" TextAlignment="Center"></TextBlock>

This will give you a UI very similar to the Android one. Press F5 to launch it in the emulator. You’ll see something like Figure 6.

6 Running Ported UI

Obviously this is not a very pretty UI, but it shows how you can get started with the porting. By tweaking the properties, or by using Expression Blend as a WYSIWYG tool you can make the UI much nicer. But for the sake of brevity, we’re going to leave it this way visually for the rest of this article.

There’s one more thing that you’ll need to edit in your XAML before you continue with the code, and that is to give names to each of the controls. In Android you use android:id within the XML declaration. In Windows Phone 7, you use Name, like this:

<StackPanel Orientation="Vertical">
    <TextBlock Text="Welcome to StckPckr7 for Windows Phone"></TextBlock>
    <StackPanel Orientation="Horizontal" Margin="0,20,0,0">
        <TextBlock Text="Enter a Ticker"></TextBlock>
        <TextBox Name="TextBox1" Text="" Width="200"></TextBox>
        <Button Name="Btn1" Content="Go"></Button>
    <Slider Name="Slider1" Maximum="100" Value="50" Margin="0,20,0,0"></Slider>
    <TextBlock Text=" -- Buy    Sell --" TextAlignment="Center"></TextBlock>

You don’t need to name all the controls, just the ones that you want to address in code. You’ll see how to do that in the next section.

Porting the Code

Step 1. Understanding how the View Definition and View Code are Connected

In Android, you’ll typically write your code as an Activity that supports the view. When you compile, R.java is generated, and the code for the view, which resides in the Activity has to load the UI for its view from R.java using code like:


Where, in this case, the view is defined using Main.xml.

The code for a Windows Phone 7 view is a little more tightly bound with its view definition. Typically, if you have a view called MainPage.xaml, you’ll write the code for it in MainPage.xaml.cs. If you look at the Solution explorer for your project you’ll see this. See Figure 7.

7 Connecting XAML Code CS

This is a process that Microsoft developers call ‘Code-behind’, where the code for the page is ‘behind’ the page. You could call the code file anything you like, as long as the class it compiles to is recognized by the page. If you look right at the top of the XAML page, you’ll see that it defines its code class using the x:Class node. So, in this case you’ll see:


This means that the MainPage class contains the code for this view. Take a look at MainPage.xaml.cs, and you’ll see that it defines the MainPage class:

public partial class MainPage : PhoneApplicationPage

So now you can write your code within this class, and it will handle the UI defined in MainPage.xaml.

Step 2. Handling Application or View Lifecycle Events

In an Android application, you’ll typically do any code-based initialization of your UI in the onCreate function. This function gets called as your application is creating the view, but before it renders it. Thus, you want to put code in there that initializes your UI components (such as setting the Seekbar Maximum and current points), so that they are ready before they are drawn. Here’s the full code for the onCreate in our app.

public void onCreate(Bundle savedInstanceState) {
  final EditText edt = (EditText)findViewById(R.id.editText1);
  seek = (SeekBar)findViewById(R.id.seekBar1);
  Button btn = (Button)findViewById(R.id.button1);  

  btn.setOnClickListener(new OnClickListener() 
        public void onClick(View v) 
            String strTicker = edt.getText().toString();   
            catch(Exception ex)
                // Do nothing

If you look up Activity.onCreateView using the API Mapping tool you’ll be shown that the equivalent in Windows Phone 7 is called Application_Launching. This is true, but not entirely true.

Application_Launching fires before your Application loads and renders its UI. But if your UI has a class underpinning it, a better way to manage the initialization of that class would be to do it in the constructor of that class. That way the UI objects can be ‘local’ variables, instead of the ‘global’ ones that they would have to be if you were addressing them from a global class. It’s better object-oriented programming that way. For reference though, you should explore the Application lifecycle events. They are stubbed out for you in Visual Studio in App.xaml and App.xaml.cs.

But for the purposes of this app, any initialization that we do to the UI should be done in the MainPage() constructor. In our Android application, the code did three things:

  • Get a reference to the EditText and call it edt, so we can reference it in code
  • Get a reference to the SeekBar and call it seek, so we can reference it in code
  • Get a handle to the button, call it btn, and add an OnClickListener event handler

In our Windows Phone 7, the process is a little simpler

  • We don’t need to get a reference to the TextBox, to reference it in code. By naming it using Name in the XAML, we can already access it using the name TextBox1
  • Similarly, we can reference the Slider (corresponds to the SeekBar) using its name as defined in XAML
  • Similarly, we can reference the Button directly by its name, but we still need to add an event handler for it.

If you’ve never used Visual Studio before, follow the next steps carefully to see one of the cooler auto complete features. Open up MainPage.xaml.cs and put the cursor in the constructor function.

Type ‘bt’, and you’ll see a menu appear with Btn1 in it. It recognizes that you have this object. Hit the TAB key, and it will be filled out for you.

Type a dot ‘.’, and then the letters ‘C’, ‘L’ and ‘I’. You’ll see that the menu follows your typing, and by now ‘Click’ will be at the top of the list. Hit TAB again to fill it out.

Now here’s the really cool part. Type ‘+=’ and a little grey box will appear hinting that you need a new Routed Event handler. Press TAB, and the code will be inserted. Press TAB again, and the full stub for the event handler will be generated and inserted for you! This makes it so much easier than having to remember the event handler function syntax and return types. Your code should look like this now:

public MainPage()
    Btn1.Click += new RoutedEventHandler(Btn1_Click);

void Btn1_Click(object sender, RoutedEventArgs e)
    throw new NotImplementedException();

It’s a lot less coding than you had in the Android activity. Let’s now implement the Click event handler for the button. First, let’s see the Java code from the Android version again:

btn.setOnClickListener(new OnClickListener() 
        public void onClick(View v) 
            String strTicker = edt.getText().toString();   
            catch(Exception ex)
                // Do nothing

Whenever the user presses the button, the event handler reads the content of the EditText, creates a string out of it and passes it to analyze ticker. Doing this in C# is very similar. Update Btn1_Click to the following:

void Btn1_Click(object sender, RoutedEventArgs e)
  String strTicker = TextBox1.Text;

You can use try..catch() in C# exactly the same way you use it in Java. I’ve just omitted it here because it isn’t necessary in the C# version of the analyzeText function which you’ll see next.

Step 3. Handling the Pure Java Code

So, thus far you’ve seen how first to migrate your UI, defined in XML, to a XAML based one. Then you saw how XAML and C# work together to provide a code-behind for the View, in a similar manner to a Java activity. You then saw some of the application lifecycle, how to run code upon starting up the view.

Finally you saw how to reference UI controls from within your code, and ‘wire-up’ event handlers so that you can write code that responds to events in the application. Finally we’ll look at meat of the Java app, namely the code that gets the user’s input, retrieves data from the web, analyzes it, and uses this analysis to provide feedback to the user.

3.1. Creating the Yahoo Finance URI

The Java Code for this app can be broken down into 3 steps. The first is to create a URI for the data service. In this case we’re using Yahoo financial data, which is retrieved as CSV (Comma Separated Values) using an HTTP call. There’s a nice tutorial for this syntax here: http://www.gummy-stuff.org/Yahoo-data.htm

Here is the Java code to do this:

// Create the Yahoo URI  
Calendar today = Calendar.getInstance();
int today_day = today.get(Calendar.DATE);
int today_month = today.get(Calendar.MONTH) + 1;
int today_year = today.get(Calendar.YEAR);
Calendar start = Calendar.getInstance();
start.add(Calendar.MONTH, -2);
int start_day = start.get(Calendar.DATE);
int start_month = start.get(Calendar.MONTH) + 1;
int start_year = start.get(Calendar.YEAR);

StringBuilder uri = new StringBuilder();

It find’s today’s date, and converts that into day, month and year values, and then the date 2 months ago, doing the same, and inserting these into a StringBuilder that builds the URI.

While Windows Phone 7 has a ‘Calendar’ object, it’s actually a UI control that represents a calendar. So don’t get thrown off by this! In C# the equivalent to the Java Calendar is the DateTime class.

3.2. Creating an HTTP request to get the data, and reading the response

The next step is that the Java Android code creates an HttpClient object to manage the connection to the service, an HttpGet object to represent the action that will be taken on that service (an HTTP request is typically a POST or a GET, and in this case it’s a GET), and an HttpResponse object to execute the command on the client and read the response.

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri.toString()));
HttpResponse response = client.execute(request);

Using the API mapper, I found that the WebClient class might be a close match to what I want to do for HttpClient. WebClient also has an asynchronous call to read the contents of a URL, so I used the following code:

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(uri.ToString()));

With the code-insert provided by the TAB key when typing the second line, I had an event handler function created for me. So, in this case once the phone reads the data from the URI, it will call back to that function, thus not locking up any threads.

At this point, in Java, you would use a BufferedReader to read the data in line by line. Each line is CSV, so when it is read as a String, you can ‘split’ it by commas. The data item we want (closing price) is the fifth item, so once we split the script, it is added to an ArrayList. Here’s the code:

in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) 
String[] rowData = line.split(",");
Double dummy = new Double(rowData[4]);

In C#, we do exactly the same thing. Some changes needed to be made, because the reader was called ‘in’ in Java. This is a reserved word in C#, so we can’t use it. Other than that, the code is very similar, except that C# doesn’t support the ArrayList for Dynamic arrays, so List<Double> was used instead:

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    System.IO.StreamReader instream = new System.IO.StreamReader(e.Result);
    instream.ReadLine(); //Read the first line
    String line;
    List<Double> closePrices = new List<Double>();
    while ((line=instream.ReadLine())!=null)
      string[] rowData = line.Split(',');
      Double dummy = new Double();
      dummy = Convert.ToDouble(rowData[4]);

3.3 Processing the Data

The final step is to analyze the data, by calculating the Bollinger Bands, figuring out their envelope, and then figuring out where the current price lies in this envelope, as a percentage figure, with bottom being 0% and top being 100%.

Explaining the statistical analysis behind this is beyond the scope of this article, but in a nutshell, the average over the range is calculated, and then the standard deviation is calculated from that. The top band is the average + 2 standard deviations, the bottom is the average – 2 standard deviations.

Here is where Java and C# are very similar, and you’ll see from the code that only minor tweaks were needed – mostly because the C# program uses a List<Double> instead of the array list, so it’s API is a little different, and because it doesn’t require casting to get variables in or out.

You’ll see that the Math libraries are almost identical, with Java ‘Math.pow’ having ‘Math.Pow’ equivalent in C#, and similar for ‘Math.sqrt’ and ‘Math.Sqrt’. Here’s the Java Code:

Double nAverage = nTotal/closePrices.size();
Double sum=0.0;
for (int i=0; i<closePrices.size(); i++)
    sum+= Math.pow((Double) closePrices.get(i) - nAverage, 2);
Double nDeviation = Math.sqrt(sum/(closePrices.size()-1));
Double bollingerTop = nAverage + (2*nDeviation);
Double bollingerBottom = nAverage - (2*nDeviation);
int nToday = closePrices.size()-1;
Double bCloseToday = (Double) closePrices.get(nToday);
Double range = bollingerTop - bollingerBottom;
Double value = bCloseToday - bollingerBottom;
Double score = 100*value/range;

And Here’s the C#:

Double nAverage = nTotal / closePrices.Count;
Double sum = 0.0;
for (int i = 0; i < closePrices.Count; i++)
    sum += Math.Pow(closePrices[i] - nAverage, 2);
Double nDeviation = Math.Sqrt(sum / (closePrices.Count - 1));
Double bollingerTop = nAverage + (2 * nDeviation);
Double bollingerBottom = nAverage - (2 * nDeviation);
int nToday = closePrices.Count - 1;
Double bCloseToday = closePrices[nToday];
Double range = bollingerTop - bollingerBottom;
Double value = bCloseToday - bollingerBottom;
Double score = 100 * value / range;
Slider1.Value = score;

So now, if I run the Windows Phone 7 version of the application, and type AAPL as I did with the Android one, I get the same results. See Figure 8.

8 The Ported Application


In this article you saw how to port an Android application from Java in Eclipse to Windows Phone 7 using Visual Studio. You learned about the Windows Phone Interoperability Bridges website, and saw how you can use this to understand the Windows paradigms for Java controls and objects. You saw how the XML UI could be moved to XAML, and then explored how the application lifecycle and event wire up worked in Visual Studio. Finally you wrote the code that handled the user input and output, and saw how the application can run on a Windows Phone 7.

Laurence MoroneyLaurence Moroney
View Author

Laurence Moroney is the owner of netNavi.tv, a software consulting firm based in Seattle that specializes in mobile and cloud computing. He's the author of too many computer books to count, including the popular 'Introducing Silverlight' series, as well as an upcoming book on Windows 8. As well as computer books, he's the author of the popular 'Fourth World' series of Young Adult Novels.

androidDiscussionTutorialswindows phonewindows phone discussionwindows phone tutorials
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form