Friday, December 23, 2016

Hola World

Hola World – First Steps with Android

Hello World! In this post we’re going to create our very first Android application! We’re going to download Android Studio and other prerequisites. Then we’re going to create a new Android Studio project and write a little app such that the user can type in his or her name, press a button, and the app will display “Hello ” and the name of the user in the middle of the screen.

Prerequisites

Before we start, we’re going to need to install some software that will allow us to develop Android apps. First, go to this linkand download and install Android Studio. With that installation, we have everything we need to write Android apps! To verify, open up Android Studio and click Configure → SDK Manager. In the dialog that pops up, on the bottom left, click Show Package Contents, and, under Android 6.0, you’ll want to make sure the following things are checked:
  • Android 6.0 Platform
  • Intel x86 Atom_64 System Image
  • Under the SDK Tools tab, Intel x86 Emulator Accelerator (HAXM installer). Follow this guide to install HAXM to boost emulator performance. (For Windows, replace <sdk> with C:\Users\<username>\AppData\Local\Android\sdk. For Mac, replace <sdk> with /Users/<username>/Library/Android/sdk where <username> is your login name.

Creating a New Project

Now that we have everything we need for Android Studio, we’re going to create our very first Android app! Opening Android Studio, click “Start a new Android Studio project” and type in something like MyFirstAndroidApp for the project name. We can type in anything we want for the company domain, but we can use lastname.com where lastname is your last name (i.e. deshpande.com). This company domain is just used to uniquely identify your app in the Google Play Store. The project location can just be any path in your filesystem where you want to store the project.
After clicking next, change the minimum SDK to Android 6.0 Marshmallow. Choose Empty Activity and we’ll just hit next past the following screen since we’re ok with just a single MainActivity. Then click Finish and Android Studio should create our project!
Hello Android – 1

Creating an Android Virtual Device

Now that we’ve created our project, we want to run it on the emulator so we can see it on our computer. The Android emulator is essentially a barebones version of the Android operating system running in a window on your computer. If we had an Android phone running Android 6.0, we could configure it to enable USB debugging and run it directly on the device. However, this post won’t assume you have one so we’re going to use the emulator instead.
On the top toolbar, find the app icon that corresponds to the AVD Manager (looks like a phone with an Android peeking up from the bottom) and a dialog should pop up with a button: Create Virtual Device. Afterwards, we can choose any device to emulate, such as the Nexus 5X or Galaxy Nexus or Nexus 6P. We can even customize our device’s screen size and density, but we’ll go with the Nexus 5X for now. Feel free to choose whatever device you’d like! On the next page, we need to select the Intel x86 Atom_64 System Image. After naming the device anything we want, we can click Finish. After some time, we should have a new virtual device we can run our apps on! We can click the green arrow in the dialog and Android Studio will launch the device. Note that it will take some time for Android Studio to launch the emulator!
Hello Android – 2
If the emulator is too large, we can always decrease the size of it by clicking the pencil icon in the AVD dialog and changing the size, as well as any other specs we want to change, like screen resolution. We can then exit out of the AVD window and then click the green Run icon on the top toolbar of Android Studio to compile our app to run on an emulator or other connected device. When the “Choose A Device” dialog box pops up, then select the emulator and click OK. In a few seconds, our app should be running on the emulator!
Hello Android – 3

Personalized Hello World

Now that we’ve created a very simple Hello World app, we can start to make it a bit more complex by adding UI elements. Let’s open up the activity_main.xml file in the Project view under app → res → layout. If you don’t see the Project view, there’s a small tab on the left titled Project, or you can press Ctrl + 1 or Cmd + 1. In the design view that comes up, we can click on the text (called a TextView ) and delete it. Then, on the palette on the left, we can drag-and-drop an Person Name EditText to the top left of the screen under the ToolBar that says “MyFirstAndroidApp.” When dragging it to that position, make sure the semi-transparent overlay says alignParentLeft andalignParentTop before you drop it in the view. Drag the right handle until the EditText  reaches the far right of the screen and the overlay says alignParentRight.
These overlays help to anchor our view to it’s parent’s view, the screen in this case. To summarize, alignParentLeft will align the current view’s left side flush with its parent’s left side. This works similarly for the other properties.
Similarly, drag out a Button and position in below the EditText and centered on the screen (overlay should say centerHorizontal  andbelow=editText ). We can change the text of the button to “Submit” by double-clicking on the Button and changing the text in the popup. Finally, we can drag-and-drop a Large Text TextView  to the dead center of the screen (popup should say centerHorizontal  andcenterVertical ). To get rid of the text in the  TextView , we can double-click the  TextView  and clear it out.
Hello Android – 4

Wire Up the Connections

Now that we have these UI elements, we actually want to do something with them. We want our user to enter their name, click the button, and the name will appear in the center of the screen. From this, it seems like all of our work will be done when the button is clicked. We need to wire our Button  so that when it’s clicked, we want to execute code that extracts the text from theEditText  and puts it in the TextView . Let’s go back to our layout file and click on the Button. In our MainActivity.java (located in app → java → com.lastname.myfirstandroidapp), afteronCreate(Bundle savedInstanceState) , add the following method definition:
When typing it in, you’ll notice that Android Studio will help by providing autocomplete suggestions. You should press enter when you find the one you need so that Android Studio can automatically add import statements (like pressing enter when typing View ). Now we can go back to our layout file and click on the Button. In the properties pane on the bottom right, find the onClick property and click in the box. A dropdown should be available and have our method signature in there. We can select our method signature, and that’s all it takes to wire our button to call the code in our buttonClicked method when the button is pressed.

Coding the Button Click

Now we can go back to the method in our source code and fill it in with the following lines:
The first line retrieves a reference to the EditText  we created. The call to findViewById(int)  takes an integer key. There is a class that Android Studio manages and creates simply called R  (stands for resources) and allows us to access all of the XML data like layouts, UI elements, and images that are in the res (also stands for resources) folder. This is the mechanism that Android Studio uses to access XML elements in Java. In our case, we didn’t change the ids of the EditText  and TextView so they areeditText  and textView  by default, and, since they’re ids, they’re in the id  inner class of R . It should be noted to NEVER modify this class! It’s auto-generated and managed by Android Studio’s unique id references so any changes will break all of our references!
The findViewById(int) method returns an object of class View and we can typecast it to what we want it to be. It’s helpful to give useful ids to our UI elements so that we can be sure what subclass ofView it is, whether it’s an EditText , TextView , Button , or other UI elements. Similarly, the second line of the code snippet grabs a reference to our TextView .
In the third line, we grab the text out of the EditText  using it’sgetText()  method. However, the getText()  method returns aCharSequence , which is an interface. We can convert this to a String  (which actually implements CharSequence ) by calling toString()  on that variable. Finally, we can set the text of the TextView  to be “Hello ” plus the name plus an exclamation point using thesetText(CharSequence) method. This is all it takes to create our app! Now we can run our app using the same green run icon and view the results!
Hello Android – 5
Bonus: You might notice that when clicking on the EditText, we have to manually clear it out first. A way to prevent this is to clear it like we did for the TextView , and changing the hint property of the EditText  to say something like “Enter your name” for example. The hint property shows up as a transparent overlay on top of the EditText  that disappears when you click on the EditText .

Conclusion

In this post, we created our very first Android app! We first started by installing Android Studio and the necessary tools we needed to code our Android app. Then we created a virtual device so that we could run our application on it. After creating a blank Android Studio project, we first ran it on the emulator to test the emulator and the default project. Then we removed the UI elements and added our own view. Then we coded the button so that when it was pressed, it ran code in our MainActivity class. We finally ran it and saw the results of our first Android app! For the complete source code, click here.