Tag Archives: app

Send SMS from Android app with Xamarin

In this tutorial you will learn how to make an Android app that can send SMS messages. Firstly, we will create a button that can send a pre-determined message to a pre-determined number. We will then extend the app by adding text fields where the user can enter a number and their message.

This is what the app will look like at the end of this tutorial…

smsapp

Step 1

To get started, open Xamarin and click File > New and select Android App from the list of templates. We will be writing this app in the C# language.

sms1

Step 2

Give your app a name. In this example, the app is called SMSApp and Modern Development has been selected as the Target Platform.

sms2

Step 3

Confirm the project and solution name as well as the folder the project will be stored in. Then click on Create.

sms3

Step 4

Open the Main.axml file in the Resources > Layout folder and delete the ‘Hello world, click me!’ button.

sms4

Step 5

Drag a new Button element from the Toolbox on to the screen. Rename its Id to @+id/sendButton and change the Text value to Send SMS.

sms5

Step 6

Now open the MainActivity.cs file to add the code. Delete the code that is highlighted below.

sms6

Step 7 

Click on the Project menu and then select the Project Options (it will be the name of your app project – here it is called SMSApp Options).

sms7

Step 8

Select Android Application from the list and then in the Required Permissions list, check the SendSms option and click on OK. This will allow the app to send SMS messages.

sms8

Step 9

Add the using Android.Telephony; line to the top section of the code.

sms9

Step 10

Define the sendButton as a Button element in your code.

sms10

Step 11

Add the following highlighted line of code to the OnCreate method so that you can access the button element from the screen.

sms11

Step 12

Now create a button click event. Type in sendButton.Click+= then press the spacebar. Double-click the option to create the SendButton_Click method.

sms12

Step 13

Inside the SendButton_Click method, add the following highlighted code.

sms13

There are two values that you need to change. The phone number (shown as 0123456789 above) needs to be changed and also the SMS message contents (shown as Hello world above). Change these values as you like. You can also get values from existing variables here or from user input in text fields. Now go and test your app on a phone with a working SIM card.

Adding user input

Now we will allow the user to enter in a number and a message to send. We will need to add a couple of text labels and text fields to the screen.

Step 14

Open the Main.axml file. Add two Text (Medium) elements and two Plain Text elements as shown below. The Text (Medium) elements should ask the user to enter a number and enter a message.

sms14

Step 15

Rename the first Plain Text element (under Enter a number) to @+id/numberEditText. Rename the second Plain Text element (under Enter a message) to @+id/messageEditText.

sms15a

sms15b

Step 16

Go back to the MainActivity.cs code. Modify the code by adding the highlighted lines of code shown below. You firstly need to define the EditText elements in the MainActivity class (lines 11-12) and then allow the code to access these elements from the screen (lines 22-23). Then you need to modify the SendButton_Click method so that the text entered by the user (the phone number and the desired message) are saved in string variables (lines 31-32). These variables are then used in line 33.

sms16

That’s it! Now go and test your completed app.

Improving the Android Temperature Converter App

In this tutorial we will look at how to improve the code in the Temperature Converter App for Android from the previous tutorial. If you have tested the app yourself, you might notice that the app works great when the user enters only numbers. However, what happens when a user enters nothing at all? The app will crash!

We will look at how to prevent such errors from occurring so that the app won’t crash if the user accidentally (or deliberately) enters non-numeric values or nothing at all – this is something known as data validation. This is what the app will look like…

Android Temperature Converter app (with data validation)
Android Temperature Converter app (with data validation)

The code below is from the same app but has some new code added to it. All of the code is commented, explaining what each new line does. None of the design elements (buttons, labels, text fields) have been changed in any way.

using Android.App;
using Android.Widget;
using Android.OS;
// need to add using System; to access the Math functions
using System;

namespace TemperatureConverter
{
  [Activity (Label = "TemperatureConverter", MainLauncher = true, Icon = "@mipmap/icon")]
  public class MainActivity : Activity
  {
    Button cButton;
    Button fButton;
    TextView resultTextView;
    EditText temperatureTextEdit;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

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

      cButton = FindViewById<Button> (TemperatureConverter.Resource.Id.cButton);
      fButton = FindViewById<Button> (TemperatureConverter.Resource.Id.fButton);
      resultTextView = FindViewById<TextView> (TemperatureConverter.Resource.Id.resultTextView);
      temperatureTextEdit = FindViewById<EditText> (TemperatureConverter.Resource.Id.temperatureTextEdit);

      cButton.Click += CButton_Click;
      fButton.Click += FButton_Click;
    }

    void FButton_Click (object sender, System.EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = temperatureTextEdit.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse (tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create fResult variable which stores result of C to F conversion
          float fResult = temp * 1.8f + 32f;
          // Change fResult to decimal data type and round to 2 decimal places
          decimal fResultRounded = Math.Round ((decimal)fResult, 2);
          // Display result on the screen
          resultTextView.Text = fResultRounded.ToString () + " degrees Fahrenheit";
        }
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultTextView.Text = "Enter numbers only";
        }
        // If nothing was entered by user, ask user to enter a number
      }
      else {
        resultTextView.Text = "Enter a number to convert";
      }
    }

    void CButton_Click (object sender, System.EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = temperatureTextEdit.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse(tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create cResult variable which stores result of F to C conversion
          float cResult = (temp - 32f) / 1.8f;
          // Change cResult to decimal data type and round to 2 decimal places
          decimal cResultRounded = Math.Round((decimal)cResult, 2);
          // Display result on the screen
          resultTextView.Text = cResultRounded.ToString () + " degrees Celsius";
        } 
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultTextView.Text = "Enter numbers only";
        }
      }
      // If nothing was entered by user, ask user to enter a number
      else {
        resultTextView.Text = "Enter a number to convert";
      }
    }
  }
}

Adding more screens to an Android app

In this tutorial, you will learn how to add multiple screens to an Android app. We will use the existing Android Temperature Converter app from one of the earlier tutorials to look at how to add more screens to apps and link each screen with buttons.

This is what the two screens of the app will look like:

ms_app_example

Watch the video below or scroll down to read the step-by-step instructions and sample code.

Video

Step 1

Drag a Space element on to the screen underneath the buttons and text view items.

ms1

Step 2

Now go to the Layout tab on the Properties panel and change Height to 100dp.

ms2

Step 3

Drag a Button element on to the screen under the Space element. Rename its Id to @+id/helpButton and change the Text value to Help. This button will link to a ‘Help’ screen that will provide information on how to use the app or how to get support. Save the file.

ms3

Step 4

Next to the layout folder, click the cog icon and then Add and New File…

ms4

Step 5

Select a new Android Layout and call it Help. Then click New.

ms5

Step 6

Your new Help.axml file should appear in the layout folder. Add a Text (Large) element to the top of the screen and change the Text value to Instructions. Then add a Multiline Text element to the screen, change its Text value to be the instructions for the app.

ms6

Step 7

Now add a Button element. Change its Text value to Go back and its Id to @+id/backButton. Save the file.

ms7

Step 8

Now go to the project folder and click on the cog icon. Click Add and New File…

ms8

Step 9

Create a new Activity file called HelpActivity. Click New. This file will contain the code for the Help screen.

ms9

Step 10

Open the HelpActivity.cs file and add the following line of code to link the Help.axml screen file to the HelpActivity.cs code file. Save the file.

ms10
Click the image to see a larger version.

Step 11

The next thing to do is to go back to the MainActivity.cs file to link the Help button to the Help.axml screen. Firstly, define the Help button in the code by adding these lines of code.

ms11
Click the image to see a larger version.

Step 12

Create a click event for the helpButton Button element.

ms12
Click the image for a larger version.

Step 13

Add the following line of code to the top section of the MainActivity.cs file.

ms13

Step 14

Inside the new HelpButton_Click method, add the following code. We will create a new intent that will open the other screen (the Help screen) when the button is clicked.

ms14
Click the image to see a larger version.

Step 15

Now go back to the HelpActivity.cs file and add this code for the Back home button so that when the user presses that button they will go back to the main screen. Save your files.

ms15
Click the image to see a larger version.

That’s it! Now go and test your app. It should have two screens like the ones shown below that open when you click on the buttons linking the screens.

ms_app_example

Sample code

Here is the C# sample code for the MainActivity.cs file:

using Android.App;
using Android.Widget;
using Android.OS;

using Android.Content;

namespace TemperatureConverter
{
  [Activity (Label = "TemperatureConverter", MainLauncher = true, Icon = "@mipmap/icon")]
  public class MainActivity : Activity
  {
    Button cButton;
    Button fButton;
    TextView resultTextView;
    EditText temperatureTextEdit;

    Button helpButton;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

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

      cButton = FindViewById<Button> (TemperatureConverter.Resource.Id.cButton);
      fButton = FindViewById<Button> (TemperatureConverter.Resource.Id.fButton);
      resultTextView = FindViewById<TextView> (TemperatureConverter.Resource.Id.resultTextView);
      temperatureTextEdit = FindViewById<EditText> (TemperatureConverter.Resource.Id.temperatureTextEdit);

      helpButton = FindViewById<Button> (TemperatureConverter.Resource.Id.helpButton);

      cButton.Click+= CButton_Click;
      fButton.Click+= FButton_Click;

      helpButton.Click+= HelpButton_Click;
    }

    void HelpButton_Click (object sender, System.EventArgs e)
    {
      var intent = new Intent (this,typeof(HelpActivity));
      StartActivity(intent);
    }

    void FButton_Click (object sender, System.EventArgs e)
    {
      float temp = float.Parse (temperatureTextEdit.Text);
      float fResult = temp * 1.8f + 32f;
      resultTextView.Text = fResult.ToString () + " degrees Fahreheit";
    }

    void CButton_Click (object sender, System.EventArgs e)
    {
      float temp = float.Parse (temperatureTextEdit.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultTextView.Text = cResult.ToString () + " degrees Celsius";
    }
  }
}

Here is the sample C# code for the HelpActivity.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace TemperatureConverter
{
  [Activity (Label = "HelpActivity")]			
  public class HelpActivity : Activity
  {
    Button backButton;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

      // add this line of code to link this file to the Help screen
      SetContentView (Resource.Layout.Help);

      backButton = FindViewById<Button> (TemperatureConverter.Resource.Id.backButton);
      backButton.Click+= BackButton_Click;

    }

    void BackButton_Click (object sender, EventArgs e)
    {
      var intent = new Intent (this,typeof(MainActivity));
      StartActivity(intent);
    }
  }
}

Improving on the iOS Temperature Converter App

In this tutorial we will look at how to improve the code in the Temperature Converter App for iOS from the previous tutorial. If you have tested the app yourself, you might notice that the app works great when the user enters only numbers. However, what happens when a user enters nothing or enters something other than numbers (such as a letter or other character)? The app will crash!

We will look at how to prevent such errors from occurring so that the app won’t crash if the user accidentally (or deliberately) enters non-numeric values or nothing at all. This is something known as data validation.

The code below is from the same app but has some new code added to it. All of the code is commented, explaining what each new line does. None of the design elements (buttons, labels, text fields) have been changed in any way.

Sample code

Here is the new and improved code for the ViewController.cs file.

// need to add using System; line to access math functions
using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      //  Create a button touch event for the Convert to Celsius button
      cButton.TouchUpInside+= CButton_TouchUpInside;
      //  Create a button touch event for the Convert to Fahrenheit button
      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse (tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create fResult variable which stores result of C to F conversion
          float fResult = temp * 1.8f + 32f;
          // Change fResult to decimal data type and round to 2 decimal places
          decimal fResultRounded = Math.Round ((decimal)fResult, 2);
          // Display result on the screen
          resultLabel.Text = fResultRounded.ToString () + " degrees Fahrenheit";
        }
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      // If nothing was entered by user, ask user to enter a number
      }
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse(tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create cResult variable which stores result of F to C conversion
          float cResult = (temp - 32f) / 1.8f;
          // Change cResult to decimal data type and round to 2 decimal places
          decimal cResultRounded = Math.Round((decimal)cResult, 2);
          // Display result on the screen
          resultLabel.Text = cResultRounded.ToString () + " degrees Celsius";
        } 
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      }
      // If nothing was entered by user, ask user to enter a number
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Creating your first iOS app

This tutorial will show you how to create a Temperature Converter app for iOS devices using Xamarin. We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. The app will look like this…

iosapp

Although we will be using Xamarin for designing and coding the app, you will still need to have XCode installed on your Mac device (click here for detailed installation instructions).

Watch the video below or scroll down to view the step-by-step instructions and sample code.

Video

Step 1

To get started, open Xamarin and begin a New Solution.

ios1

Step 2

Select App under iOS and then select Single View App (C#). Click on Next to continue.

ios2

Step 3 

Give your app a name. In this case, it will be called TempConverter. You also need to select a minimum iOS version you want to support. In this case, the target version is iOS 9.1. Make sure the target version is either an older or same version of iOS that you will be using to run the app on. Click Next to continue.

ios3

Step 4

Now just confirm the project and solution name (making sure it is not the same name as a solution that already exists in your projects folder) as well as the project folder location and click Create.

ios4

Step 5

Once the new solution has loaded, Xamarin will automatically open a file called AppDelegate.cs. Don’t worry about this file for now as we won’t really be changing anything there. The two files that we will be working with are the Main.storyboard file (for adding the buttons, text labels, and text boxes) and ViewController.cs (for coding the functionality).

ios5

Double-click the Main.storyboard file to open it. It may take a minute to load. The storyboard is where you will add your user interface elements such as buttons, text boxes and text labels. Choose the iPhone device that you want to use as the preview for your storyboard eg. iPhone 6.

ios6

Step 6

In the Toolbox panel (use the search box to find and add the Toolbox to your layout if you don’t see it there), scroll down until you see Label (you can also search in the Toolbox for the Label element.

Drag a Label element on to the phone screen where you would like to place it.

ios7

Step 7

Change the Text value in the Properties panel (on the Widgets tab) to ‘Enter temperature in degrees:’.

ios8

Step 8

Drag the edges of the Label element to resize it so that you can see all of the text.

ios9

You can also change the colour of the text, the font and alignment (eg. align to center) from the Properties panel.

ios10

Step 9

Drag a Text Field element from the Toolbox on to the screen under the text label. Change its Placeholder text to ‘Temperature in degrees’. Resize the Text Field and center-align the text.

ios11

Step 10

Drag two Button elements on to the screen and resize them to fit their text. Change the first button’s text to ‘Convert to Celsius’ and the second button’s text to ‘Convert to Fahrenheit’.

ios12

Step 11

The last element to add is the text label which will display the result of the temperature conversion. Drag a Label element on to the screen and change its default Text to 0, change its Colour and Font size/style. You can also change the Alignment to center.

ios13

Step 12

Now we need to name each of the screen elements so that they can be accessed by the code. Firstly, click on the temperature text field and change its Name to tempTextField.

ios14

Step 13

Now give the ‘Convert to Celsius’ button the Name cButton.

ios15

Also set the Name of the ‘Convert to Fahrenheit’ button to fButton.

ios16

Step 14

Lastly, click on the text label which will display the conversion result and change its Name to resultLabel. Now is a good time to save the Main.storyboard file (Click File > Save).

ios17

Step 15

Now its time to do some coding. Open the ViewController.cs file. In this file, click inside the ViewDidLoad method and add the code highlighted below. This code will add a button touch event that will occur when the user touches to Convert to Celsius button. When we create the cButton.TouchUpInside event it will also automatically create a new method CButton_TouchUpInside which will contain the code that will convert a temperature to Celsius.

ios18

Step 16

We now need to also create a button touch event for the Convert to Fahrenheit button and a method that will contain its code.

ios19

Step 17

Now let’s add the code for the FButton_TouchUpInside method first. This method will be called when the Convert to Fahrenheit button is pressed by the user. Add the highlighted code below. Firstly, a float variable called temp is created to store the temperature value that the user enters into the text field as a float value. Then a variable called fResult will convert the temperature from Celsius to Fahrenheit and store the result as a float value. Lastly, the text on the resultLabel element will display the result and the text ‘degrees Fahrenheit’ at the end of the sentence eg. ’68 degrees Fahrenheit’.

ios20

Note: You may need to resize the fResult label element in the Main.storyboard file so that it can fit the result and text.

Step 18

We can now add the code for the Convert to CButton_TouchUpInside method to run the conversion when the Convert to Celsius button is pressed. Add the highlighted code to this method shown below. Then save your code (File > Save).

ios21

Step 19

Now go back to the Main.storyboard file and select the Text Field element. In the Properties panel and on the Widget tab, scroll down and change the Keyboard Type to Decimal Pad so that numbers with decimal place can be typed in and the most suitable keypad is displayed. Save the file.

ios22

Step 20

At this point, the app will work and will allow the user to type in a temperature (as a whole or decimal number) and convert it to either Celsius or Fahrenheit. However, after the user has typed in a number they should be able to hid the keyboard if it is no longer needed.

Before testing the app we will add a little piece of code that will allow the keypad to be dismissed by the user when it is no longer needed. To do this, go back to the ViewController.cs file and start typing the highlighted line of code (where it is shown below). As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code. This will create a new override method called TouchesBegan. Inside this method we will add some code to dismiss the keyboard.

ios23
As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code.

Add the following code inside the new override method called TouchesBegan to allow the keyboard to be dismissed when typing has been completed by the user. Then save the file.

ios24

Finishing up

All of the coding is done. Congratulations – you have made your first iOS app using Xamarin and the C# programming language! Remember to save your files.Now just select a type of iPhone model you would like to test this app on and click on the Build button to start testing/emulating the app.

ios25

And this is what the completed app should look like…

ios26

What next?

Test your app thoroughly. Are there any problems with your app? Does it crash under some circumstances? Is there any way it could be improved. Jump into the next tutorial to see how this app can be improved.

Sample code

You can download the sample code for the ViewController.cs file here:

using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      cButton.TouchUpInside+= CButton_TouchUpInside;

      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse(tempTextField.Text);
      float fResult = temp * 1.8f + 32f;
      resultLabel.Text = fResult.ToString () + " degrees Fahrenheit";
    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse (tempTextField.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultLabel.Text = cResult.ToString () + " degrees Celsius";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Publishing your Android app

This tutorial explains how to publish your app and create an .APK file that can be installed on an Android phone. For this tutorial, we will be using the CookieClicker app. You might also want to change the app icon and details before publishing your app.

Watch the video below or scroll down to read the step-by-step instructions.

Video

Step 1

To get started, open the solution that you wish to publish in Xamarin. You will need to create an Android Signing Key before you can publish your app. To do this, click on the Xamarin Studio Community menu and select Preferences (this might be on the File menu in Windows).

p1

Step 2

In the Preferences dialog, click on Android Signing Keys (under Publishing) and click on Create New Key.

p2

Step 3

Give your new signing certificate an alias (name) and create a password (at least 6 characters long). Then select the validity length (how many years the certificate will be valid for) and fill in at least of the text boxes with something (eg. just provide your name or your city name). Click on OK to continue.

p3a

You should then see your new signing key/certificate in the list of Android Signing Keys. Click on OK to exit the Preferences dialog.

p3b

Step 4

Select the Project menu and change your Active Configuration to Release. This will allow you to publish your app (you can change this back to Debug after you have published your app so you can return back to coding and testing your apps).

p4

Step 5

Select the Build menu and then click Archive for Publishing.

p5

Step 6

Now click on Sign and Distribute.

p6

Then select Ad-Hoc to save the app file (the .apk file) to your computer. Click on Next.

p7

Step 7

Select your signing key from the list and click Next.

p8

Then confirm you are happy with the app details and file size and click Publish.

p9

Step 8

Lastly, choose where to save your .apk file and click on Save. You can now share this file online or copy it to your phone (either by USB cable or email). You can also upload it to the Google Play store for other people to download.

p10

Step 9

After you have published your app, remember to change the project’s active configuration back to Debug by clicking on the Project menu > Active Configuration > Debug.

Important note

If you decide to upload your app to the Google Play store you must make sure that you do not violate any copyright laws (eg. check that you are not using other people’s images or sound files and that you app is not the same as an existing app). Also, make sure you have your parents’ permission before uploading any apps to the Google Play store.

Changing your Android app icon

Before you publish your app you might want to change your application icon. In fact, some application marketplaces might reject an Android application that does not have its own icon. To get started, you will need to create a logo and save it as a PNG file somewhere on your computer.

Watch the video below or scroll down for the step-by-step instructions.

Video

Step 1 

Open your solution in Xamarin and then open the Resources and drawable folders. Click on the cog icon next to the drawable folder and then click Add > Add Files from Folder…

ic1

Step 2

Select the folder which contains the icon file and then click on Open.

ic2

Step 3

Check the icon that you want to use and then click OK.

ic3

Choose Copy the file to the directory and then click OK.

ic4

You should now see the icon file in the drawable folder.

ic5

Step 4

Click on Project and then select [YourAppName] Options. For this example, we need to click on CookieClicker Options.

ic6

Click on Android Application and then change the Application icon field to @drawable/[YourIconName]. For the example below, it is @drawable/cookie_icon. Then click on OK.

ic7

Alternatively, you can change the icon in the MainActivity.cs file code.

ic8

Now when you go to Build > Archive for Publishing, you should see your app icon there (publishing your app will be explained in the next tutorial).

ic9

Making a Cookie Clicker game for Android

For our second Android app project, we will create the most pointless but addictive game in the world…a cookie clicker! A basic version of it will look like the image shown below, but you can extend this game as much as you like. You will also learn how to add image buttons to your app screens.

cc1

Watch the video below or scroll down to read the step-by-step instructions and view the sample code.

Video

Step 1

You will need to create a new Android App solution in Xamarin called CookieClicker. Click on New Solution (or File > New Solution) to get started.

cc2

Step 2

Choose Android App as the type of new solution and then click Next.

cc3

Step 3

Set the App Name to CookieClicker (one word – no spaced). Choose Modern Development as the Targeted Platform using the default theme and click on Next.

cc4

Step 4

Keep the project and solution names as CookieClicker, select a project location to store your files in and click on Create.

cc5

Step 5

Open the MainActivity.cs file (if it does not automatically open) and delete the lines of code highlighted below. These lines of code won’t be needed for this project.

cc6
Click to see larger version of this image.

Step 6

Now open the Main.axml file located in the Resources > layout folder.

cc7

Step 7

Click on the button that says “Hello World, Click Me!”. We won’t need this button so it can be deleted. Either click on it and press the Delete key on your keyboard, or right-click the button and select Delete.

cc8

Step 8

From the Toolbox (if you don’t see it, you can search for the Toolbox from the search bar), scroll down under Images & Media and drag an ImageButton element on to the phone screen.

cc9

Step 9

Now you will need to download a cookie image to your computer (preferably a PNG image file with a transparent background). A free public-domain image has been provided below. Click on the image to open the full-size version and then save the image to a folder on your computer and name it cookie.png.

Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain - free for commercial use, no attribution required)
Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain – free for commercial use, no attribution required)

Step 10

Select the ‘drawable’ folder inside the Resources folder and click on the small cog icon. Then select Add > Add Files from Folder.

cc10

Step 11

Select the folder that contains the cookie image file and click on Open.

cc11

Step 12

Select the cookie.png file (or whatever yours is called) and make sure the checkbox is checked. Then click on OK.

cc12

Step 13

Make sure you select Copy the file to the directory and then click on OK.

cc13

Step 14

Now you should see cookie.png in the drawable folder.

cc14

Step 15

Click on the ImageButton element on the phone screen and change the Src property to @drawable/cookie (you do not need to include the .png file extension).

cc15

Step 16

Now we need to make sure the image fits properly on the screen. Click on the drop-down arrow next to the Scale Type property and change it to fitCenter.

cc16a

You can then also click on the ImageButton and drag the little circle up to change the height of the image. You can also change the width of the image this way. Alternatively, go to the Layout tab on the Properties panel and change the width and height values there eg. 435dp for the height. Note: sizes of elements are measured using the ‘dp’ unit on Android.

cc16b

cc16c

If you go to the Source tab, your code for the Main.axml file might look like the code shown below. However, your code could be a little different so don’t change the code here unless you are sure you know what you are doing.

cc16d

Step 17

In the Designer view, drag a Text (Large) element on to the phone screen under the ImageButton. This will be used to display the number of clicks.cc17

Step 18

From the Widget tab on the Properties panel, change the Text value from Large Text to 0 clicks. At the same time, change its Id from @+id/textView1 to @+id/cookieTextView . You can also change the Gravity value to center so the text is centered.

cc18

Step 19

Click on the ImageButton element (the cookie) and change its Id from @+id/imageButton1 to @+id/cookieImageButton – now you need to save the Main.axml file.

cc19

Step 20

Now we can add the code! Open the MainActivity.cs file and create an integer variables called clicks that is given an initial integer value of 0. This variable will be created inside the MainActivity class, as highlighted below.

cc20

Step 21

We also need to define the ImageButton element and the TextView element in the code. This is highlighted in the lines below. Make sure to use the correct names for each element.

cc21

Step 22

Inside the OnCreate method (under the SetContentView (Resource.Layout.Main); line), we need to now setup the ImageButton and TextView element.

cc22

Step 23

The next thing you need to do is create a click event for the cookie ImageButton by adding the line cookieImageButton.Click+= CookieImageButton_Click; – this will create a new method called CookieImageButton_Click which will contain the code that will increase the number of clicks and display the number of clicks each time the ImageButton is tapped.

cc23

Step 24 

Inside the CookieImageButton_Click method, add the following two highlighted lines of code. The clicks++; line will increase the clicks variable by 1 each time the button is tapped, and the next line of code is responsible for converting the clicks variable value to a string and displaying the clicks variable’s value on the screen as well as the text “clicks!” at the end eg. 25 clicks!

cc24a

Now save your work. All of the coding is done! Now you could extend this app by adding extra buttons to purchase items when a certain number of cookies are clicked (using if statements) or increase the number of cookies by a different amount. You could add extra text labels or buttons too. However, let’s test that this app works properly first. Click on the Build button after selecting a virtual device to run the app on (if you don’t know how to do this, refer to the previous tutorial – Creating your first Android app with Xamarin).

cc25a

cc25b

Here is the source code for the MainActivity.cs file:

using Android.App;
using Android.Widget;
using Android.OS;

namespace CookieClicker
{
  [Activity (Label = "CookieClicker", MainLauncher = true, Icon = "@midmap-hdpi/icon")]
  public class MainActivity : Activity
  {
    int clicks = 0;

    ImageButton cookieImageButton;
    TextView cookieTextView;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

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

      cookieImageButton = FindViewById<ImageButton> (CookieClicker.Resource.Id.cookieImageButton);
      cookieTextView = FindViewById<TextView> (CookieClicker.Resource.Id.cookieTextView);

      cookieImageButton.Click+= CookieImageButton_Click;

    }

    void CookieImageButton_Click (object sender, System.EventArgs e)
    {
      clicks++;
      cookieTextView.Text = clicks.ToString () + " clicks!";
    }
  }
}

 

Creating your first Android app with Xamarin

This tutorial explains how to use Xamarin and the C# programming skills you have gained so far in this tutorial series to start making your very own Android apps. In this tutorial, we will develop a Temperature Converter app for Android which can convert between Celsius and Fahrenheit temperatures.

This is what the app will look like:

Temperature Converter app for Android
Temperature Converter app for Android

So let’s get started! You can watch the video below or read through the step-by-step instructions below. The C# sample code for this project is also at the bottom of this page.

Video

Step 1

Click on New Solution to create a new solution for this project.

aa1

Step 2

Select the Android App template and click Next.

aa2

Step 3

Give your app a name. For this example, we have called the app TemperatureConverter. Select a target platform. Here, we have chosen Modern Development to make this app compatible with modern Android phones. If you choose Latest and Greatest you will need to download the latest Android Simulators. Choose Default theme and click Next.

aa3

Step 4

Choose the location to store your project and click Next. You can keep the project name as it is or give it a different name.

aa4

Step 5

After Xamarin creates your new project it will most likely automatically open the MainActivity.cs file (if not, double-click it from the Solution folders list on the left side of the screen). By default, you will already have some lines of code in there for an example app. Delete the lines of code shown in the image below (we will be adding our own buttons so we don’t need the one that is already there).

aa5

Step 6

In the Solution list on the left side of the screen, click to open the Resources folder, then open the layout folder, and double-click to open the Main.axml file. This will open the storyboard for our main screen in Designer view.

aa6

You will see the default button ‘Hello World, Click Me!’ there. You can right-click this button and click on Delete to remove the button.

aa6b

Step 7

From the Toolbox on the right side of the screen, scroll down until you see the Text (Small) element (under Form Widgets). Drag the Text (Small) element on to the storyboard in the Designer view.

aa7

Step 8

Now drag a Plain Text element (under Text Fields) from the Toolbox on to the storyboard under the Small Text element you added in the previous step.

aa8

Step 9

Now you need to drag two Button elements (found under Form Widgets in the Toolbox) on to the screen.

aa9

Hint: You can search form screen design elements in the Toolbox using the search box.

Step 10

The last screen design element to add is a Text (Large) (large text label) to display the result of the temperature conversion.

aa10

Step 11

Click on the Small Text element and in the Properties panel (and Widgets tab) change the Text property from ‘Small Text’ to ‘Temperature (in degrees)’. Hit the Enter/Return key on your keyboard and you should see the text label change on the phone screen.

aa11

Step 12

Change the Text property in the Properties panel for both buttons. The first button should say ‘Convert to Celsius’ and the second button should say ‘Convert to Fahrenheit’.

aa12

Step 13

Now change the large text label so that it says ‘0’ is the default value before any result is displayed.

aa13

Did you know? These values can also be changed from the Source view if you prefer as shown below. Be careful not to accidentally change any of the other code though! Some of your code might be different to the code below – don’t change it unless you know exactly what you are doing.

You can alternatively change the text and IDs of elements in the Source view if you prefer that over the Designer view.
You can alternatively change the text and IDs of elements in the Source view if you prefer that over the Designer view.

Step 14

Now that we have changed the text that displays on the labels and buttons, we need to change the actual names of the elements.

Click on the temperature text field and change its Id in the Properties panel. Its Id needs to change from @+id/editText1 to @+id/temperatureEditText.

aa14

Step 15

Now change the name (Id) of the text label that will display the conversion result. Click on the result label and change its Id from @+id/textView2 to @+id/resultTextView.

aa15

Step 16

Repeat the last step for the two buttons changing their Id’s to @+id/cButton for the Convert to Celsius button and @+id/fButton for the Convert to Fahrenheit button. Make sure you save the Main.axml file by pressing Cmd + S (on Mac) or Ctrl + S (on Windows).

aa16

Step 17

Now we can add the functionality to the app. Open the MainActivity.cs file. Firstly, we will define the different text label and button elements in the code. Inside the public class MainActivity: Activity class, add the following highlighted code:

aa17
Click to see larger version of image if you can’t read the code.

Step 18

Now we need to assign the values from the Main.axml file to each element in the MainActivity.cs file. Under the SetContentView (Resource.Layout.Main); line of code, add the following highlighted code:

aa18

Now we will be able to use these elements in a new method that will convert the temperature input.

Step 19

We need to create click events for both the ‘Convert to Celsius’ button and the ‘Convert to Fahrenheit’ button. To do this, add the code below. You will notice that this will create two new methods for our click events. These methods will be used when the click event is fired (when the buttons are tapped by the user) so the relevant conversion code will need to be in each click event method.

aa19

Step 20

Now let’s add the code for the FButton_Click method first (the method which will convert from Celsius to Fahrenheit). We will create a new float variable that will contain the value entered by the user in the temperatureEditText text field. The value will also need to be converted (parsed) from the string data type to the float data type.

aa20

Step 21

A float variable will need to be created that will store the result of converting from Celsius to Fahrenheit. In the conversion formula, we need to add the letter f at the end of each value that will need to be parsed as a float.

Step 22

Now we can access the resultTextView element and display the conversion result on that text label. It will also need to be converted to a string. We can add the text “ degrees Farenheit” to the end of the result displayed.

Step 23

Now we just need to write the code for the CButton_Click method by creating the variable which will store the value entered by the user, creating a variable which will store the Fahrenheit to Celsius conversion result, and then displaying the result on the text label. After adding the code (as shown below), save the file.

aa23

Step 24

Now go back to the Main.axml file in the Designer view and click on the temperatureEditText text field element. In the Properties panel, scroll down until you see Input Type (under Input Format on the Widget tab). Change the Input Type to NumberDecimal. Then save the file.

aa24

That is all of the coding done! Now we can test the app but first we must select an Android Virtual Device to emulate the app.

Step 25

Click on the Device button next to Debug on the top toolbar and select a compatible Virtual Device that has been installed. The Virtual Device must be the same or higher API level than the targeted device selected in Step 3 (eg. the Modern Development option is API level 16). The Nexus 5 virtual device shown below is API level 19. If you don’t have a compatible virtual device to select then you will need to click on Manage Android Devices and download a compatible virtual device (they are free to download).

To install and use virtual Android devices for testing, it is suggested you install the Xamarin Android Player. Once installed, you can download a virtual device (eg. Nexus 5) and use it on your Mac or PC to test the Android apps you build. You can also use the built-in Android Virtual Device manager but it is much slower!

aa25a

Once a compatible virtual device has been selected you can run the app by clicking on the Build icon on the top toolbar.

aa25b

The Xamarin Android Player will open and load the selected virtual device. It may take a minute. Unlock the device screen and your app should open!

aa25c
Unlock the simulated phone by dragging the padlock icon to the side. Your app should then automatically open.
aa25d
Enter a number value in the text field and then press the relevant conversion button to see the conversion result.
Success!
Success!

Congratulations, you just made your very first Android app using Xamarin and the C# language! In the next tutorial we will make the same app for an iPhone.

Later on we will also look at how to export an Android app so that you can install it on your own phone.

Sample C# code

Here is the sample code for the MainActivity.cs file. Note that the app, solution and project are all named TemperatureConverter.

using Android.App;
using Android.Widget;
using Android.OS;

namespace TemperatureConverter
{
  [Activity (Label = "TemperatureConverter", MainLauncher = true, Icon = "@mipmap/icon")]
  public class MainActivity : Activity
  {
    Button cButton;
    Button fButton;
    TextView resultTextView;
    EditText temperatureTextEdit;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

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

      cButton = FindViewById<Button> (TemperatureConverter.Resource.Id.cButton);
      fButton = FindViewById<Button> (TemperatureConverter.Resource.Id.fButton);
      resultTextView = FindViewById<TextView> (TemperatureConverter.Resource.Id.resultTextView);
      temperatureTextEdit = FindViewById<EditText> (TemperatureConverter.Resource.Id.temperatureTextEdit);

      cButton.Click+= CButton_Click;
      fButton.Click+= FButton_Click;

    }

    void FButton_Click (object sender, System.EventArgs e)
    {
      float temp = float.Parse (temperatureTextEdit.Text);
      float fResult = temp * 1.8f + 32f;
      resultTextView.Text = fResult.ToString () + " degrees Fahreheit";
    }

    void CButton_Click (object sender, System.EventArgs e)
    {
      float temp = float.Parse (temperatureTextEdit.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultTextView.Text = cResult.ToString () + " degrees Celsius";
    }
  }
}

 

Using Adobe Shape CC app to turn sketches into Illustrator drawings

This video tutorial explains how to use the Adobe Shape CC app (on iOS and Android) to take a photo of a hand-drawn sketch and turn it into an SVG vector graphic which can be opened and edited in Adobe Illustrator CC.

Watch the video below or on YouTube.