This blog features a walk-through of an app that was developed in Visual Studio 2015 using Xamarin and deployed to an Android mobile device. I will be getting and displaying stock information by calling a public web service and passing in a Stock Ticker. The web service is one of the first ones that came up when I did a search for a Stock API. You could really plug in a similar service and get things to work without changing too much code.
Let’s get started by creating a new Android project: Blank App. Alternatively, you could choose Cross-Platform project to make the app available on both Android and iOS.
If you don’t have Xamarin for Visual Studio installed yet, click here for install instructions.
I named the project StockQuote and clicked OK.
I like to begin by defining all the data objects that we will be working with, which are in the JSON response. I created a new class called ‘Stock.cs’ and added the following code.
Now let’s work on the screen design. This part is specific to Android and would be somewhat different if you were designing a screen for iOS. Open the main.axml file in the layout folder under Resources. You’ll notice a Designer and Source tab at the bottom. When you are in the Designer view, the toolbox should be displayed on the left that you can use to drag controls onto the view. In the source tab is the actual code (obviously). If you’re a .NET web developer (like me) and are new to Android design, this part might take some getting used to.
Below is the source code for the screen layout.
Next we need to add the following line of code to the OnCreate function in MainActivity.cs:
SetContentView(Resource.Layout.Main); //This will load the screen
If we hit “F5” to run at this point, we will get the screen below. I am using one of the Android emulators to execute. If you have an Android device, you can plug it into an available USB port to execute as another option.
Before handling the Button_Click event, let’s write the function that calls the web service. Right click on the project and add a new class called “Service.cs”. We’ll need to add the following method to call the service and return the response.
Next let’s add another class called Quote.cs and add the following method that will parse out the result and populate our Stock Object.
Finally, we code the Button_Click event. This will call the GetQuote method that we wrote earlier and populate the textboxes on the screen.
Now when we run the application, enter a valid ticker and click on the Get Quote button, you will get the following display.
That’s it! A simple Android application to track your favorite Stocks.