Android Lesson 1 - Hello World
https://kabartobi.blogspot.com/2017/01/android-lesson-1-hello-world.html
This tutorial was written and tested to work with Android 5.1.1, Java JDK 1.70_21, Android Studio 1.5.1 and Android API 11 – 23
In this beginning tutorial, we will create a basic “Hello World!” Android application using the Android Studio IDE. While Android applications are often created with large amounts of Java, no extensive knowledge of Java is needed as all requisite code will be provided here. The Android Studio IDE is a powerful and helpful tool for creating Android applications. It will allow you to code, build, debug, manage version control, and much more!
What Will I Learn and Accomplish?
One of the very first things most developers do when trying out a new programming language or tool is create a “Hello World” program. Essentially it is a virtual dipping of the toes into the pool to make sure needed tools are installed and configured correctly. This will likely be the first app you will code in Android. As this Hello World app relates to Android, you will be installing the Java SE JDK, android Studio and Android SDK. Additionally, you will learn the very basics of an Android app: you will create your very first activity and layout, as well as modify the Android manifest file, and define your own text strings and color values. You will have the option of running the app in the Android Virtual Device (AVD) and/or your own connected Android phone or tablet.
Steps Covered in this Tutorial:
Install Java JDK
Install Android Studio and Android SDK
Code the Hello World Application
Create the Project
Coding the MainActivity
Creating the activity_main Layout File
Setting the MainActivity ContentView
Building the activity_main Layout
Modifying the Android Manifest
Deploy the App to Android Virtual Device (AVD)
Deploy the App to Mobile Device
Tools Used in This Tutorial:
Java Development Kit (JDK) – Current build is JDK 8u65 at time of writing
Android Studio IDE – Current version is 1.5.1 at time of writing
Android SDK – Included with Android Studio download
Install Java JDK
The best place to start our tutorial is by gathering the tools we will need to build our Hello World app. As we will be building for Android, will will need the Java Development Kit (JDK) upon which the Android operating system relies heavily. The vast majority of applications for Android devices are coded (at least in some part) in Java.
There is a very good chance that you already have some form of Java on your computer . While this helps you run some apps and plugins, we need something more- the actual environment that allows us to code in Java: the JDK! If you aren’t sure if you have it installed- or if you know that you need it- head on over to the Oracle site and download the most recent version of Java SE. Make sure you click the button to accept the license agreement, then select the appropriate download link based on your operating system.
Once downloaded (yes it’s a big file so be sure your data connection can handle it) go ahead and install it like you would anything else. It may prompt you to close some Java dependent applications, but that is completely normal.
After the install is complete, I recommend rebooting your machine and proceeding to the next step. If you have any problems installing the JDK, head on over to StackOverflow, enter your symptoms and find the help you need fast!
Install Android Studio and Android SDK
Download and installation of Android Studio and the Android SDK will (time-wise) be the longest part of this tutorial. You can download them from the official Android website. Unless you already have it installed, it’s just a task we have to deal with. The upside is that we only have to download them once and they are included together in the same download. Like the Java SE (JDK) download, this one is big… you will want to make sure you have up to 1.5 GB available for download and install.
After you’ve gotten a bit older and your download is complete, go ahead and install Android Studio. If you need help installing, check out the official Android Developer Docs.
Once installation is complete, go ahead and open up Android Studio. You should see a Welcome screen with some quick start options. If so head on to the next part of the tutorial.
Code the Hello World Application
Create the Project
To simplify the Hello World experience a bit, we are going to use one of the quick start options available to us. Go ahead and select “Start a new Android Studio project” from the Welcome screen. Presently you are whisked away to the New Project Configuration screen. This is all pretty straightforward but if it is your first time ever seeing such a thing, here are a few helpful tips.
Once you have the configurations complete, click next to go to the Target Android Devices screen.
For this tutorial we are only going to be building for “Phone and Tablet” so make sure it’s the only one checked. In the Minimum SDK dropdown, select the lowest version of Android that you want to be allowed to run this app. The lower the version, the more devices and people you can reach; however, it also can severely limit the features available for you to use (Android 6 Marshmallow is more feature rich than is Android 3 Honeycomb). For this tutorial I am setting the minimum to API 11 (Android 3.0).
Click next and then when asked about adding an activity, select “Add No Activity.” We are going to build our own Main activity, layout and Manifest entry!
Coding the Main Activity
Once the project is created, you’re not going to see much excitement. You are likely met by a screen telling you that no files are open. Let’s fix that. Since we opted to build our own activity instead of having Android Studio generate one for us, we need to do that now.
On the far left bar (with vertical text), you will see “1: Project.” Click on it and the project navigation tree shows up. With “Android” selected at the top of the nav tree, expand the “app” folder and then the “java” folder. You should now see something similar to the following.
Under the “java” folder, notice that I have two packages with the name com.johnriggsdev.helloworld. The top one is the one we will use for building our app. The second is automatically generated by Android Studio for unit testing purposes (if we wanted to do that); we will be ignoring the package with the name “androidTest” next to it.
Right-click (control-click on Mac) the top helloworld package generated for you. Hover over/click New and then select “Java Class.”
Give your new class the name “MainActivity” and click OK. Android Studio will generate the MainActivity.java class file for you. You should see your package name at the top, the name of the class, and possibly a comment that you created the file (depending on your settings).
Go ahead now and make your code match the following. (In the first line be sure to leave the package name as your package name)
MainActivity.java
Look at line six of our code public class MainActivity extends Activity. This line defines our MainActivity as an activity. What is an activity? Well according to the official Android documentation, an activity is “an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.”
In simpler terms, in order to do anything in Android we must have at least one activity. Larger and more complex apps may have hundreds of unique activities, but for our purposes we need only one (the one that will display Hello World!) and we’ve just created it by extending the Java class Activity.
In the definition, we see that each activity is given a window in which to draw its user interface. We do this by creating and associating a layout file. We don’t yet have a layout file to associate with our MainActivity; so let’s create it now!
Creating the activity_main Layout File
Look again at your project’s navigation tree. Layout file are generally store in a layout folder within the res (resources) folder. If you expand the res folder, you will likely see the drawable, mipmap and values folders but no layout.
Right-click (control-click on Mac) and select New >>> Android Resource Directory. Set the resource type to layout, make sure the directory name also says layout, then click OK.
So now that we have created our layout folder, let’s go ahead and create our first layout XML file to associate with MainActivity. Right-click (control-click on Mac) on the layout folder and choose New >>> Layout Resource File. (If you don’t see this option, you may not have selected Layout as the Resource Type when you created the directory.)
On the New Resource File dialog, enter the File Name as “activity_main” and replace LinearLayout with “RelativeLayout” for the root element. When creating XML layout files in android, the general naming convention is to associate it first with the type of Android element it is used for, then with the name of that element- everything in lowercase and spaced with the underscore character. Since our layout is to be used with our main activity MainActivity, the layout file name becomes activity_main. If we were to create one for a hypothetical class called BankAccountFragment, the layout file would be named fragment_bank_account and so on. The reason we use the underscore "_" character is because in XML, there can be no white space (spaces) in names.
Go ahead and leave the Source Set and Directory Name fields just as they are. Click OK to create the layout_main.xml file.
Once the file is created, you will probably be presented with a design interface that looks like a phone with a blank screen. This is the visual editor bundled in with Android Studio. It can be useful and many developers with use it to quickly generate UI elements. As the visual design editor auto-generates code, that doesn’t help us actually learn the code so let’s switch over to the text editor. In the bottom-left of the design window, choose the “Text” tab. You should now be presented with the text version of our activity_main.xml file similar to the following.
Setting the MainActivity ContentView
Now that we have a layout file to play with (and for our MainActivity to draw to) we need to create an association between the two. Within the MainActivity class code, you should have a block that Overrides the onCreate function of the parent Activity class:
To go beyond the previously stated function of creating an association between MainActivity and activity_main, this new line of code does the following. When Android creates the MainActivity as an Activity, it overrides (redefines) the onCreate method that belongs to the Activity class. setContentView(int layoutResID) is a function that states which layout file (as represented by an integer located in the auto-generated ‘R’ file) holds the information this activity needs to should be drawn to the screen.
*** The next paragraph is a little bit more advanced and can be skipped if needed ***
This may feel like magic and may be a bit confusing at first. This is perfectly fine. In hopes of helping shed a little more light on what may be a confusing concept, here is a little more about the R file. As you add more classes, layouts, objects and directories to your project, Android needs a way to sort and keep track of all these things. It does so by generating the R file and adding/removing them to/from it; each item in the file contains a reference to its location in memory as well as a name we can easily understand. This is useful to use because it stores these objects residing in memory as integers we can reference when needed. It is important to note that although you may reference an item in the R file by its integer (really by its associated name), YOU SHOULD NEVER DIRECTLY MODIFY THE R FILE!. The file is generated/destroyed/altered outside of your control and so the memory address-integer associations may change as well. What does not change is the name of the item in the file (unless you change/delete it in your code). We made reference to
Now that our activity has a layout to draw to, we can start defining what that layout should contain.
Building the activity_main Layout
If you go back into the activity_main.xml file we created a bit ago, you will see a couple things have been defined for us. The first is the XML version number and type of encoding. The second is the RelativeLayout (assuming you changed it over from LinearLayout when creating the file). Within the RelativeLayout header tag, we see the xmlns schema defined- we will ignore this. We also see two other attribute defined: layout_width and layout_height. These will have to be defined for almost all xml elements you add in layout files. Each of these are set to “match_parent.” This means that this RelativeLayout’s height and width will match its parent’s height and width. Because MainActivity is the main activity in our app, Android will give it access to the entire screen. Because there are no other layouts that restrict the height and width available to activity_main, the RelativeLayout will also fill the entire screen.
Between the
Notice that instead of “match_parent” for the height and width, we are using “wrap_content.” This will ensure that the TextView is only as wide as it needs to be to display the text and 10dp padding. “layout_centerInParent” is set to true so that the TexView will center itself relative to the parent RelativeLayout. This is the reason I actually used RelativeLayout instead of LinearLayout. RelativeLayout allows you to define the positions of elements relative to each other whereas in a LinearLayout, everything is rendered in a line.
If you click back on the Design tab and go to the visual editor, you will still only see a blank phone screen. This is because we have 1) not defined any text for our TextView and 2) no custom colors have been defined so only the default light gray is rendered. Let’s fix this. Click back on the text tab to return to the text editor.
In the project nav tree, expand the values folder found under the res directory. You should see two files: strings.xml and styles.xml. The strings.xml file is where we will define our text string but first let’s create a third file called colors.xml. As you likely guessed, right-click (control-click on Mac) on the values folder, select New >>> Values Resource File and enter “colors” as the File Name.
In colors.xml, go ahead and define three colors for us to use in our activity_main layout.
We could use the color hex values directly in our layout file; however, by defining them with easy to understand names in the colors.xml file, we can simply call them by name, no matter how big our app gets! By no means are you stuck using the colors I’ve picked; if you want to define your own color codes, w3schools.com has a fantastic color picker tool you should bookmark. When defining your own color codes for Android, the first two characters after the octothorpe/hashtag/pound sign (“#”) are the alpha value (transparency- 00 is complete transparent and FF is opaque). The next 6 characters are the color’s code.
Open up your strings.xml file and let’s define a string for us to use in a similar fashion.
Head back into activity_main.xml and amend it to resemble the following. Note that code has been added to both the RelativeLayout and TextView elements.
You may feel like it is extra effort to define colors and string in a separate file instead of writing them directly into our layout code; there are times when I share this feeling. However, it is considered bad practice to do this because if you have a large app and need to make a change to a color or text string, you will have to manually hunt down every single instance of it to make the change. If you keep all these things defined in a central locations, it is very easy to make one change that will then change all related instances. Another reason is that if you wish to have different languages for your app, it is easy to translate one strings file while nearly impossible to hunt down all strings in your code.
BEGINNER CODING CHALLENGE:
Do you see in the TextView that I have two dimensions hard-coded into the code (10dp and 24dp)? Can you create a file called dimens.xml that defines these dimensions with names then use them in the code? I will post my solution at the end of the tutorial. If you need a hint, check out the Android documentation.
Modifying the Android Manifest
The final step in coding our app is to tell Android which activity is the main activity- that is which activity is the starting point. We do this through the Android Manifest. The AndroidMAnifest.xml is a file which contains all of the activities, permissions and features used by the application. You know when you download an app from the Play Store and it tells you all the things the app will be able to do on your device? Well those things are listed explicitly in the manifest. If a feature or permission is not listed in here, it may not be used.
The same goes for activities. The manifest keeps a list of activities so it has reference to them when needed. Often whenever I can’t get an activity to run in an application, it’s because I’ve forgotten to add it to the AndroidManifest.xml file. In your project nav tree, under the app directory, you should see a manifests folder. Expand it and then open the AndroidManifests.xml file. Make the file resemble the following.
That’s it for coding the app! Now let’s build and run it!
Deploy the App to Android Virtual Device (AVD)
If you click the green arrow in the top bar in Android Studio, the Device Chooser dialog pops up. This is where you can choose to either run your code in an Android Virtual Device (AVD) or on a connected phone/tablet. In this section, make sure the radio button for Launch Emulator is selected. You will probably see Nexus 5 API 21 x86 selected as the AVD; you can leave this as is. Then click OK.
One nice thing about running the AVD is that you can actually emulate many different hardware profiles. The downside is that it can be very slow and doesn’t have all of the components your phone or table does (like accelerometers, cameras, LEDs, etc…).
Once the emulator launches (often behind other active windows), use it just like you would a phone or tablet. Click and drag your mouse to swipe-unlock. Once unlocked, that app usually launches automatically. If it doesn’t, click on the icon in the bottom-center of the screen. It’s the icon with a circle with 6 squares in it.
Click on the “Hello World” app to launch.
Once it launches, you should see our Hello World TextView! If not, walk back through section 3 and see if there is anything you missed.
If you do see our Hello World message, congratulations! You have successfully created you first Android app! Check the next section for tips on deploying to a real device.
Deploy the App to Mobile Device
Apart from connecting your phone/tablet to the USB port on your computer, you need to enable USB Debugging in the Developer Options on your physical device. To access the Developer Options, navigate to your device’s setting and go to About Phone/Device. Locate the Build Number entry and tap it 10 times. Once you have, you will see a message that says you are now a developer.
Once then is done, back out to Settings and tap to enter your Developer Options. Scroll down to Debugging >>> USB Debugging and make sure the box is checked. Confirm to allow USB debugging. You are now able to build and test apps on your device!
Make sure your phone is connected to your computer via USB and click the play button in Android Studio. The Device Chooser will pop up and this time select running device, make sure your device is selected, and click OK.
Android Studio will automatically push the app to your device and will generally auto-launch; if not, check for the app in your apps list and launch it that way.
TROUBLESHOOTING:
If you connect your device via USB and it does not appear in the Device Chooser, you may need to update your drivers, disconnect/reconnect your device, adjust firewall settings to allow communication with your device, install Samsung Kies on your computer (if you have a Samsung device), or download and install the Google USB driver through the Android Studio Android SDK manager. A Google search will generally help you get your device up and running with minimal pain.
That’s It!
Assuming all went well and you got the “Hello World!” message on your device, congrats! You’ve finished the tutorial and can now successfully create and activity with layout, define custom string, color and dimension values, and deploy to a virtual or real device!
Stay tuned for more Android tutorials coming soon. Feel free to send me a message or leave a comment if you have any questions, corrections or if there is anything you would like to see in the future. Thanks for reading!
CODING CHALLENGE SOLUTION:
Here is how I solved the challenge. Your’s may be differ a bit and that’s okay; it certainly doesn’t have to be a clone of mine.
dimens.xml
activity_main.xml
What Will I Learn and Accomplish?
One of the very first things most developers do when trying out a new programming language or tool is create a “Hello World” program. Essentially it is a virtual dipping of the toes into the pool to make sure needed tools are installed and configured correctly. This will likely be the first app you will code in Android. As this Hello World app relates to Android, you will be installing the Java SE JDK, android Studio and Android SDK. Additionally, you will learn the very basics of an Android app: you will create your very first activity and layout, as well as modify the Android manifest file, and define your own text strings and color values. You will have the option of running the app in the Android Virtual Device (AVD) and/or your own connected Android phone or tablet.
Steps Covered in this Tutorial:
Install Java JDK
Install Android Studio and Android SDK
Code the Hello World Application
Create the Project
Coding the MainActivity
Creating the activity_main Layout File
Setting the MainActivity ContentView
Building the activity_main Layout
Modifying the Android Manifest
Deploy the App to Android Virtual Device (AVD)
Deploy the App to Mobile Device
Tools Used in This Tutorial:
Java Development Kit (JDK) – Current build is JDK 8u65 at time of writing
Android Studio IDE – Current version is 1.5.1 at time of writing
Android SDK – Included with Android Studio download
Install Java JDK
The best place to start our tutorial is by gathering the tools we will need to build our Hello World app. As we will be building for Android, will will need the Java Development Kit (JDK) upon which the Android operating system relies heavily. The vast majority of applications for Android devices are coded (at least in some part) in Java.
There is a very good chance that you already have some form of Java on your computer . While this helps you run some apps and plugins, we need something more- the actual environment that allows us to code in Java: the JDK! If you aren’t sure if you have it installed- or if you know that you need it- head on over to the Oracle site and download the most recent version of Java SE. Make sure you click the button to accept the license agreement, then select the appropriate download link based on your operating system.
Once downloaded (yes it’s a big file so be sure your data connection can handle it) go ahead and install it like you would anything else. It may prompt you to close some Java dependent applications, but that is completely normal.
After the install is complete, I recommend rebooting your machine and proceeding to the next step. If you have any problems installing the JDK, head on over to StackOverflow, enter your symptoms and find the help you need fast!
Install Android Studio and Android SDK
Download and installation of Android Studio and the Android SDK will (time-wise) be the longest part of this tutorial. You can download them from the official Android website. Unless you already have it installed, it’s just a task we have to deal with. The upside is that we only have to download them once and they are included together in the same download. Like the Java SE (JDK) download, this one is big… you will want to make sure you have up to 1.5 GB available for download and install.
After you’ve gotten a bit older and your download is complete, go ahead and install Android Studio. If you need help installing, check out the official Android Developer Docs.
Once installation is complete, go ahead and open up Android Studio. You should see a Welcome screen with some quick start options. If so head on to the next part of the tutorial.
Code the Hello World Application
Create the Project
To simplify the Hello World experience a bit, we are going to use one of the quick start options available to us. Go ahead and select “Start a new Android Studio project” from the Welcome screen. Presently you are whisked away to the New Project Configuration screen. This is all pretty straightforward but if it is your first time ever seeing such a thing, here are a few helpful tips.
- Application Name- Bluntly, enter whatever name you want to call your app. As this is a Hello World application, “Hello World” may be appropriate. So would “First App,” “Test,” or just about anything. The name you give your app now is the name that will appear on your device’s app list.
- Company Domain- Domains are used to help create unique package names for distribution in the Google Play Store (as you will see in the next point). It is a good idea when developing Android apps to have your own dedicated domain that you can enter here. For me I am using the domain you are on right now: “johnriggsdev.com.” If you are not going to publicly publish your app, you can pretty much use whatever domain you like. Just keep in mind that the Play Store will not let you publish under someone else’s domain without the appropriate permissions. So for now you can go ahead and enter any domain you want.
- Package Name- The general convention for naming packages for distribution on the Play Store is [reverse domain].[app name]. This helps ensure packages are uniquely named. You can edit it if you want but leaving it alone is likely the best course.
- Project Location- Just like saving any other file or group of files on your computer, where do you want it to go? Just keep in mind that folder names should not contain spaces (white space) as it can cause problems later on.
Once you have the configurations complete, click next to go to the Target Android Devices screen.
For this tutorial we are only going to be building for “Phone and Tablet” so make sure it’s the only one checked. In the Minimum SDK dropdown, select the lowest version of Android that you want to be allowed to run this app. The lower the version, the more devices and people you can reach; however, it also can severely limit the features available for you to use (Android 6 Marshmallow is more feature rich than is Android 3 Honeycomb). For this tutorial I am setting the minimum to API 11 (Android 3.0).
Click next and then when asked about adding an activity, select “Add No Activity.” We are going to build our own Main activity, layout and Manifest entry!
Coding the Main Activity
Once the project is created, you’re not going to see much excitement. You are likely met by a screen telling you that no files are open. Let’s fix that. Since we opted to build our own activity instead of having Android Studio generate one for us, we need to do that now.
On the far left bar (with vertical text), you will see “1: Project.” Click on it and the project navigation tree shows up. With “Android” selected at the top of the nav tree, expand the “app” folder and then the “java” folder. You should now see something similar to the following.
Under the “java” folder, notice that I have two packages with the name com.johnriggsdev.helloworld. The top one is the one we will use for building our app. The second is automatically generated by Android Studio for unit testing purposes (if we wanted to do that); we will be ignoring the package with the name “androidTest” next to it.
Right-click (control-click on Mac) the top helloworld package generated for you. Hover over/click New and then select “Java Class.”
Give your new class the name “MainActivity” and click OK. Android Studio will generate the MainActivity.java class file for you. You should see your package name at the top, the name of the class, and possibly a comment that you created the file (depending on your settings).
Go ahead now and make your code match the following. (In the first line be sure to leave the package name as your package name)
MainActivity.java
package com.johnriggsdev.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Look at line six of our code public class MainActivity extends Activity. This line defines our MainActivity as an activity. What is an activity? Well according to the official Android documentation, an activity is “an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.”
In simpler terms, in order to do anything in Android we must have at least one activity. Larger and more complex apps may have hundreds of unique activities, but for our purposes we need only one (the one that will display Hello World!) and we’ve just created it by extending the Java class Activity.
In the definition, we see that each activity is given a window in which to draw its user interface. We do this by creating and associating a layout file. We don’t yet have a layout file to associate with our MainActivity; so let’s create it now!
Creating the activity_main Layout File
Look again at your project’s navigation tree. Layout file are generally store in a layout folder within the res (resources) folder. If you expand the res folder, you will likely see the drawable, mipmap and values folders but no layout.
Right-click (control-click on Mac) and select New >>> Android Resource Directory. Set the resource type to layout, make sure the directory name also says layout, then click OK.
=== === ===
So now that we have created our layout folder, let’s go ahead and create our first layout XML file to associate with MainActivity. Right-click (control-click on Mac) on the layout folder and choose New >>> Layout Resource File. (If you don’t see this option, you may not have selected Layout as the Resource Type when you created the directory.)
On the New Resource File dialog, enter the File Name as “activity_main” and replace LinearLayout with “RelativeLayout” for the root element. When creating XML layout files in android, the general naming convention is to associate it first with the type of Android element it is used for, then with the name of that element- everything in lowercase and spaced with the underscore character. Since our layout is to be used with our main activity MainActivity, the layout file name becomes activity_main. If we were to create one for a hypothetical class called BankAccountFragment, the layout file would be named fragment_bank_account and so on. The reason we use the underscore "_" character is because in XML, there can be no white space (spaces) in names.
Go ahead and leave the Source Set and Directory Name fields just as they are. Click OK to create the layout_main.xml file.
Once the file is created, you will probably be presented with a design interface that looks like a phone with a blank screen. This is the visual editor bundled in with Android Studio. It can be useful and many developers with use it to quickly generate UI elements. As the visual design editor auto-generates code, that doesn’t help us actually learn the code so let’s switch over to the text editor. In the bottom-left of the design window, choose the “Text” tab. You should now be presented with the text version of our activity_main.xml file similar to the following.
<?version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
That’s it for the creating the layout file! We will soon add some element to the layout but for now, let’s go back to our MainActivity.java file and associate the newly create layout.Setting the MainActivity ContentView
Now that we have a layout file to play with (and for our MainActivity to draw to) we need to create an association between the two. Within the MainActivity class code, you should have a block that Overrides the onCreate function of the parent Activity class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
We will add our layout association directly following the super.onCreate(savedInstanceState);
line. Add the lineset ContentView(R.layout.activity_main);
so that your MainActivity.java file now looks like the following.
package com.johnriggsdev.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
To go beyond the previously stated function of creating an association between MainActivity and activity_main, this new line of code does the following. When Android creates the MainActivity as an Activity, it overrides (redefines) the onCreate method that belongs to the Activity class. setContentView(int layoutResID) is a function that states which layout file (as represented by an integer located in the auto-generated ‘R’ file) holds the information this activity needs to should be drawn to the screen.
*** The next paragraph is a little bit more advanced and can be skipped if needed ***
This may feel like magic and may be a bit confusing at first. This is perfectly fine. In hopes of helping shed a little more light on what may be a confusing concept, here is a little more about the R file. As you add more classes, layouts, objects and directories to your project, Android needs a way to sort and keep track of all these things. It does so by generating the R file and adding/removing them to/from it; each item in the file contains a reference to its location in memory as well as a name we can easily understand. This is useful to use because it stores these objects residing in memory as integers we can reference when needed. It is important to note that although you may reference an item in the R file by its integer (really by its associated name), YOU SHOULD NEVER DIRECTLY MODIFY THE R FILE!. The file is generated/destroyed/altered outside of your control and so the memory address-integer associations may change as well. What does not change is the name of the item in the file (unless you change/delete it in your code). We made reference to
R.layout.activity_main when we called the setContentView(int layoutResID) method. What this means is that in the R file, there is an integer associated with the activity_main file found in the layout folder. Since setContentView required an integer, we were able give it the appropriate integer by passing in R.layout.activity_main.Now that our activity has a layout to draw to, we can start defining what that layout should contain.
Building the activity_main Layout
If you go back into the activity_main.xml file we created a bit ago, you will see a couple things have been defined for us. The first is the XML version number and type of encoding. The second is the RelativeLayout (assuming you changed it over from LinearLayout when creating the file). Within the RelativeLayout header tag, we see the xmlns schema defined- we will ignore this. We also see two other attribute defined: layout_width and layout_height. These will have to be defined for almost all xml elements you add in layout files. Each of these are set to “match_parent.” This means that this RelativeLayout’s height and width will match its parent’s height and width. Because MainActivity is the main activity in our app, Android will give it access to the entire screen. Because there are no other layouts that restrict the height and width available to activity_main, the RelativeLayout will also fill the entire screen.
Between the
<RelativeLayout> and </RelativeLayout> header and end tags, add a TextView to our code. This is the XML element that will hold and display our text.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Notice that instead of “match_parent” for the height and width, we are using “wrap_content.” This will ensure that the TextView is only as wide as it needs to be to display the text and 10dp padding. “layout_centerInParent” is set to true so that the TexView will center itself relative to the parent RelativeLayout. This is the reason I actually used RelativeLayout instead of LinearLayout. RelativeLayout allows you to define the positions of elements relative to each other whereas in a LinearLayout, everything is rendered in a line.
If you click back on the Design tab and go to the visual editor, you will still only see a blank phone screen. This is because we have 1) not defined any text for our TextView and 2) no custom colors have been defined so only the default light gray is rendered. Let’s fix this. Click back on the text tab to return to the text editor.
In the project nav tree, expand the values folder found under the res directory. You should see two files: strings.xml and styles.xml. The strings.xml file is where we will define our text string but first let’s create a third file called colors.xml. As you likely guessed, right-click (control-click on Mac) on the values folder, select New >>> Values Resource File and enter “colors” as the File Name.
In colors.xml, go ahead and define three colors for us to use in our activity_main layout.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="black" type="color">#FF000000</item>
<item name="blue" type="color">#FF33B5E5</item>
<item name="white" type="color">#FFFFFFFF</item>
</resources>
We could use the color hex values directly in our layout file; however, by defining them with easy to understand names in the colors.xml file, we can simply call them by name, no matter how big our app gets! By no means are you stuck using the colors I’ve picked; if you want to define your own color codes, w3schools.com has a fantastic color picker tool you should bookmark. When defining your own color codes for Android, the first two characters after the octothorpe/hashtag/pound sign (“#”) are the alpha value (transparency- 00 is complete transparent and FF is opaque). The next 6 characters are the color’s code.
Open up your strings.xml file and let’s define a string for us to use in a similar fashion.
<resources>
<string name="app_name">Hello World</string>
<string name="hello_world">Hello World!</string>
</resources>
Head back into activity_main.xml and amend it to resemble the following. Note that code has been added to both the RelativeLayout and TextView elements.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_centerInParent="true"
android:background="@color/blue"
android:textSize="24dp"
android:textColor="@color/white"
android:text="@string/hello_world"/>
</RelativeLayout>
You may feel like it is extra effort to define colors and string in a separate file instead of writing them directly into our layout code; there are times when I share this feeling. However, it is considered bad practice to do this because if you have a large app and need to make a change to a color or text string, you will have to manually hunt down every single instance of it to make the change. If you keep all these things defined in a central locations, it is very easy to make one change that will then change all related instances. Another reason is that if you wish to have different languages for your app, it is easy to translate one strings file while nearly impossible to hunt down all strings in your code.
BEGINNER CODING CHALLENGE:
Do you see in the TextView that I have two dimensions hard-coded into the code (10dp and 24dp)? Can you create a file called dimens.xml that defines these dimensions with names then use them in the code? I will post my solution at the end of the tutorial. If you need a hint, check out the Android documentation.
Modifying the Android Manifest
The final step in coding our app is to tell Android which activity is the main activity- that is which activity is the starting point. We do this through the Android Manifest. The AndroidMAnifest.xml is a file which contains all of the activities, permissions and features used by the application. You know when you download an app from the Play Store and it tells you all the things the app will be able to do on your device? Well those things are listed explicitly in the manifest. If a feature or permission is not listed in here, it may not be used.
The same goes for activities. The manifest keeps a list of activities so it has reference to them when needed. Often whenever I can’t get an activity to run in an application, it’s because I’ve forgotten to add it to the AndroidManifest.xml file. In your project nav tree, under the app directory, you should see a manifests folder. Expand it and then open the AndroidManifests.xml file. Make the file resemble the following.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.johnriggsdev.helloworld">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:label="@string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
That’s it for coding the app! Now let’s build and run it!
Deploy the App to Android Virtual Device (AVD)
If you click the green arrow in the top bar in Android Studio, the Device Chooser dialog pops up. This is where you can choose to either run your code in an Android Virtual Device (AVD) or on a connected phone/tablet. In this section, make sure the radio button for Launch Emulator is selected. You will probably see Nexus 5 API 21 x86 selected as the AVD; you can leave this as is. Then click OK.
One nice thing about running the AVD is that you can actually emulate many different hardware profiles. The downside is that it can be very slow and doesn’t have all of the components your phone or table does (like accelerometers, cameras, LEDs, etc…).
Once the emulator launches (often behind other active windows), use it just like you would a phone or tablet. Click and drag your mouse to swipe-unlock. Once unlocked, that app usually launches automatically. If it doesn’t, click on the icon in the bottom-center of the screen. It’s the icon with a circle with 6 squares in it.
Click on the “Hello World” app to launch.
Once it launches, you should see our Hello World TextView! If not, walk back through section 3 and see if there is anything you missed.
If you do see our Hello World message, congratulations! You have successfully created you first Android app! Check the next section for tips on deploying to a real device.
Deploy the App to Mobile Device
Apart from connecting your phone/tablet to the USB port on your computer, you need to enable USB Debugging in the Developer Options on your physical device. To access the Developer Options, navigate to your device’s setting and go to About Phone/Device. Locate the Build Number entry and tap it 10 times. Once you have, you will see a message that says you are now a developer.
Once then is done, back out to Settings and tap to enter your Developer Options. Scroll down to Debugging >>> USB Debugging and make sure the box is checked. Confirm to allow USB debugging. You are now able to build and test apps on your device!
Make sure your phone is connected to your computer via USB and click the play button in Android Studio. The Device Chooser will pop up and this time select running device, make sure your device is selected, and click OK.
Android Studio will automatically push the app to your device and will generally auto-launch; if not, check for the app in your apps list and launch it that way.
TROUBLESHOOTING:
If you connect your device via USB and it does not appear in the Device Chooser, you may need to update your drivers, disconnect/reconnect your device, adjust firewall settings to allow communication with your device, install Samsung Kies on your computer (if you have a Samsung device), or download and install the Google USB driver through the Android Studio Android SDK manager. A Google search will generally help you get your device up and running with minimal pain.
That’s It!
Assuming all went well and you got the “Hello World!” message on your device, congrats! You’ve finished the tutorial and can now successfully create and activity with layout, define custom string, color and dimension values, and deploy to a virtual or real device!
Stay tuned for more Android tutorials coming soon. Feel free to send me a message or leave a comment if you have any questions, corrections or if there is anything you would like to see in the future. Thanks for reading!
CODING CHALLENGE SOLUTION:
Here is how I solved the challenge. Your’s may be differ a bit and that’s okay; it certainly doesn’t have to be a clone of mine.
dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="text_size">24dp</dimen>
<dimen name="textview_padding">10dp</dimen>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/textview_padding"
android:layout_centerInParent="true"
android:background="@color/blue"
android:textSize="@dimen/text_size"
android:textColor="@color/white"
android:text="@string/hello_world"/>
</RelativeLayout>

Posting KomentarDefault CommentsFacebook Comments