Login

Build your first Android Application

Objectives

  • Build a simple HelloWorld Android application to show your birthday.
  • Setup the Android Studio on your computer.
  • Installing the necessary dependencies for your first Android Application.

Let’s begin!

Android Studio is the official IDE (Integrated Development Environment) for android development, based on IntelliJ Idea. Coupled with IntelliJ’s powerful static code analysis and developer tools, android studio also comes with a gradle based build system, extensive testing tools and GitHub integration. It also offers many more features to enhance productivity letting the developer focus more on his ideas and worry less on the internal details.

 

Android

Installing Android Studio

The installation of Android Studio is based on the operating system you use.

Windows 64 bit

Step 1: Download the .exe executable file from https://developer.android.com/studio/

Step 2: Click on the executable file to launch it.

Step 3: Follow the setup wizard in Android Studio and install any SDK packages that it recommends.

 

Windows 32 bit

Android studio needs to be downloaded via a zip file as the .exe executable is not available for 32 bit windows system.

Step 1: Go to https://developer.android.com/studio/ and scroll down to download option.

Step 2: Download the .zip file for 32 bit system.

Step 3: Extract the .zip file

Step 4: Open android-studio > bin folder and launch studio.exe

 

Mac

Step 1: Goto https://developer.android.com/studio/ and scroll down to download option.

Step 2: Download the .zip file for Mac.

Step 3: Extract the .zip file

Step 4: Launch the Android Studio DMG file

Step 5: Drag and drop Android Studio into the Applications folder

Step 6: Launch Android Studio. The Setup Wizard guides you through the rest of the setup, which includes downloading Android SDK components that are required for development.

 

Linux

Step 1: Goto https://developer.android.com/studio/ and scroll down to download option.

Step 2: Download the .zip file for Linux.

Step 3: Extract the .zip file

Step 4: For a 64-bit version of Linux, make sure to first install the required libraries for 64 bit machines.

  • ubuntu: sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386
  • Fedora: sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686

Step 5: Open a terminal, navigate to the android-studio/bin directory, and execute sh.

Step 6: The Setup Wizard guides you through the rest of the setup, which includes downloading Android SDK components that are required for development.

Let us now start building applications that we can interact with!

Configuring your project window for HelloWorld app

This simple app will take a person’s name and date of birth and display a hello message on the same screen and the day of birth on a new screen if the user wishes to know the date of birth.

Step 1: Open Android Studio.

Step 2: In the Welcome to Android Studio window, click Start a new Android Studio project.

Step 3: In the Choose your project window, select Empty Activity -> Next.

Step 4: In the Configure your project window, enter the following.

  • Name: “HelloWorld”
  • Package name: “com.example.helloworld”
  • Change the project location if required.
  • Change language to java as this tutorial uses java for all its sample apps.
  • Leave minimum API level unchanged for now.
  • Check the box adjacent to This Project Will Support instant apps.
  • Check the box next to use androidx artifacts.

Step 5: Click Finish.

 

Project configuration window for HelloWorld app

 

Note:

  • Name – refers to the name of the application
  • Package name – is a unique name to identify our specific app. Package names generally follow the format domain.company.application.The domain extension could be com or org or any other valid extension, company refers to the developers company name and application refers to the app itself. Generally, app name itself is used in the application portion of package name.
  • Minimum API level – Specifies the minimum version of android needed to run the app. We leave it at the default level of API 15 which corresponds to icecream sandwich (Android 4.0.3)
  • Create a new empty activity – Checking this box automatically creates an activity for us which will be launched when we run the app. We will learn more about activities in further sections.

Review of the files that just got created

  • Make sure the project structure window is visible on the left pane.
  • If not then Goto View -> Tool windows -> Project and then make sure Android view is selected from the drop-down list at the top of that window.

Take a look at the following files.

app > java > com.example.helloworld > MainActivity

  • This is the main entry point for the app.
  • When you build and run the app, the system launches an instance of this Activity and loads its xml layout file.

app > res > layout > activity_main.xml

  • This xml file defines the layout for mainactivity’s UI.

app > manifests > AndroidManifest.xml

  • The manifest file describes the fundamental characteristics of the app and defines each of its components. Any permissions that our app needs like internet access, location access etc. should be declared in the manifest file.
  • Any new activity that we wish to add to our app also should make an entry in the manifest file. Most of the time this will be done automatically for us if we create an activity using File -> Activity -> Choose the type of activity

Gradle Scripts > build.gradle

  • There will be two files with this name: one for the project (“Project: MyFirstApp”) and one for the “app” module (“Module: app”).
  • Each module has its own build.gradle file, We will mostly work with the module’s build.gradle file to configure how the Gradle tools compile and build the app.

Run the app

We can either run the app on a real device or on an emulator. Note that the knowledge of java is a requirement to understand further.

Running the application on a real device

Step 1: Connect the device to the machine with a USB cable. If developing on Windows, you may need to install the appropriate USB driver for your device.

Step 2: Go to -> Settings -> Developer options. If developer options is not available under settings

  • Go to -> About Phone -> Scroll to bottom and tap build number 7 times.
  • Now developer options becomes available

Step 3: Open Developer options, and scroll down to find and enable USB debugging. Hit the play button.

Step 4: In the Select Deployment Target window, select your device, and click OK.

Step 5: For now we will just see a Hello World message at the center of the screen.

 

App layout on creating the project

 

Running the application on an emulator

Step 1: Hit the play button.

Step 2: In the Select Deployment Target window, click Create New Virtual Device.

Step 3: In the Select Hardware screen, select a phone device, such as Pixel, and then click Next.

 

Create emulator dialog

 

Step 4: In the System Image screen, select the version with the highest API level. If you don’t have that version installed, click Download and complete the download. Click Next.

 

System Image screen

 

Step 5: On the Android Virtual Device (AVD) screen, leave all the settings as it is and click Finish.

 

Verify Configuration dialog

 

So why did our app show Hello world after we ran it for the first time without effectively making any changes to the project?

  • As mentioned earlier, since we chose to check the box this project supports instant apps while creating our project, android studio created a MainActivity file for us and also a activity_main.xml file which includes the layout and views hierarchy corresponding to this activity.
  • If we navigate to app > res > layout > activity_main.xml file and open it, we will see that it is already populated with a constraint layout which houses a textview layout whose text attribute is set to Hello World!
  • And on navigating to app > res > layout > activity_main.xml, we see that an onCreate method is already written for us, inside which it calls setContentView method passing the activity_main layout as the argument.
  • Hence, when we launched the app, MainActivity is the apps entry point (just like main() function is the entry point to a program execution) and its onCreate method got executed inside which we are instructing it to set its initial layout as defined in the activity_main.xml file.
  • Now this xml file had a textview whose text attribute was set to Hello World and that was how we got to see Hello World on our screen.

HelloWorld is not much fun, lets go explore how to construct complex layouts and views.

Building Complex layouts

Viewgroups

Viewgroups are special views that can contain children views. It is like a main container for other views (widgets) whose positions can be described with respect to the viewgroup. Also viewgroups can be nested within other view groups allowing us to build a complex layout.

 

Different types of commonly used Viewgroups

1. Linear Layout

This viewgroup places all its children in either horizontal direction or the vertical direction. This can be specified with the android:orientation attribute which can take the value of horizontal or vertical.

Linear layout also supports assigning a weight attribute to each child which specifies how much remaining space in the viewgroup it will occupy.

Equal weights distribution to all views

To create a linear layout whose views share equal space among themselves et the layout_height attribute of each view to 0dp and assign each child view a weight of 1.

 

Linear layout with equal weights for all child views

 

Unequal distribution of weights

In unequal weight distribution we assign each view a different weight value according to how much space it should fill. As depicted in the example below we assigned each of the first two edit text views a weight of 1 and the edittext view for message a weight of 2. This implies that the edit text view corresponding to message has a higher priority and should occupy more space. So the message edit text view gets half the remaining space while the first two edit text views share the remaining space equally among themselves.

 

Linear layout unequal weight distribution

 

2. Relative Layout

This viewgroup positions its children based on relative positions (to the left of ,or to the right of) to its sibling views or in relative positions to its parent (align to the center, align to bottom etc).

Relative layout is helpful in avoiding nested views which can cause performance degradation. Many a times a deeply nested linear layout can be flattened out into a relative layout that has fewer nested views.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Here we observe that view 2 is placed below view1 making use of the relative attribute layout_below and assigning it the layout id of view1, also it uses the relative attribute layout_alignParentLeft and sets it to true signaling that it should be aligned to the left with respect to its parent layout, and it uses another attribute layout_toleftOf attribute and assigns it the id of view3 indicating it should be placed to the left of view3.

Similarly other views are placed relative to each other and the parent viewgroup.

 

Relative layout

 

Views

Creating a layout for the main activity of our helloWorld app

When we created our project an activity_main.xml file automatically gets created. So whenever we launch our app it will start the mainActivity and since inside the oncreate method setcontebtVoew is called with activity_main as argument, the layout structure defined in this xml file gets drawn on the screen as soon as the app starts.

To begin creating our layout navigate to app > res > layout > activity_main.xml

  • Add a LinearLayout as the root viewgroup and set its width and height to matchparent which implies that we want our root view to occupy the entire space on the screen. Set its orientation to vertical and optionally we may apply padding according to our needs.
  • Next create an EditText view to take the name input. Set an id attribute for it so that we can later refer to it from our MainActivity code. Set its width to match_parent and height to wrap_content so that it occupies entire width of screen but only takes as much space as needed vertically. We can set a hint attribute which lets the user know what type of input is expected in that field.
  • Create another EditText view to take date of birth with the same attributes as above but assign it a different id and change the hint attribute for this view to indicate to the user that a date of birth is expected in this field.
  • Create a TextView to display our custom hello message. Set its width and height attributes similar to above views and assign an id to it. Set the textsize attribute to 16dp and choose whatever style looks good from the autoComplete feature.
  • Create another TextView to display a message to user asking whether they want to know their birth day. Set its width to 240dp and height to Set its margin_top attribute to 120dp.This makes the view to be placed 120dp from the top of the screen. Also set its layout_gravity to center indicating that we want this view at the center of the screen horizontally. Setting gravity to center makes the text inside the TextView to become center aligned.
  • Finally add a button view with a width of 100dp and height of Set the layout_gravity to center to align the view to the center horizontally. Set its text attribute to show birth day and set its onClick attribute to sendDOB. The onClick attribute is for handling the button click. So whenever a the button is clicked it searches for a method whose name is the value of onClick attribute. In our case it searches for a method named sendDOB in the corresponding activity(in our case activity_main.xml ’s corresponding activity is mainActivity.java) and runs the code defined in that method. So when we write our MainActivity java file we need to define this sendDOB method.

This is how the activity_main.xml file will look like after following all the above steps

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

 

Static layout

 

This is just a static layout and does not seem so fun for now. In this step we will move our to MainActivity.java and add some code to make this layout respond as we had intended.

  • Inside the onCreate method start by getting references to the EditText views and the message textview which we had defined in the xml layout. The findViewById method takes in an integer id to search for and returns the view if found or null otherwise.
  • To find our EditText view which takes name input we would do

EditText nameField = (EditText) findViewById(R.id.name);

  • Here findViewById is taking the id of the view we try to find (name is the EditText’s id in this case). id.id_name automatically converts the id to an integer to pass into the findViewById function. Since findViewById returns a view object we explicitly cast it to an EditText object to store it in a variable named nameField of EditText type.
  • Similarly find the EditText view for dob and store it in dobField and find the view for message and store it in a variable named message of type TextView.
  • Now since we got a hold of these views we can call methods defined on them to manipulate their behavior at runtime.
  • Lets set the text for message TextView initially to some random text. We use the setText method to accomplish this. This method takes a string argument that we want the view to display.

message.setText(“Lets get to know each other tell me your name and birth date”);

  • Now lets add a textchanged listener to EditText to listen for changes on the EditText which takes name input. This will let us update the message view as soon as the name changes inside the EditText..When we type nameField followed by the dot the autocomplete feature will provide a list of actions that can be performed with this view. Select the addTextChangedListener from this list , pass a new TextWatcher as the argument, android studio will autocomplete the default methods of this class that we need to implement i.e. beforeTextChanged, onTextChanged and afterTextChanged.
  • We might need to make all the three nameField, dobField and message variables final since we will be trying to access them from inside the TextWatcher class.
  • We don’t have to to do anything before the text changes and as soon as the text changes so we leave beforeTextChanged and onTextChanged methods alone.
  • In the afterTextChanged method we write a simple if-else statement to look for changes in the nameField and dobField and appropriately display the correct message. getText().toString() method returns a string representation of whatever is there in EditText.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • In the first if check we see whether nameField is empty if yes we set the message asking the user to type a name
  • Else if we have a name we check if dateofbirth field is empty, if yes then ask for birthday
  • Else we have both a name and birthday so display whatever congratulatory message we want to display. In the example we are extracting the substring corresponding to the month and looking it up to see which month it corresponds to in our months Array defined at the top of the class outside onCreate method.
  • Similarly add a onTextChangedListener to dobField and declare a string variable at the top outside onCreate method and initialize it to “”. Now in the dobField’s TextWatcher’s afterTextChanged method do an if-else check to see if the date is valid or not.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • Here we first check if the length of the DOB is <10 or >10, if yes the date is invalid and we set the dob string to “” and indicate the same with a message on the message TextView.
  • Else the date is valid and we set dob to whatever date value is present in the dobField and display a greeting message to the user.
  • Finally we implement the sendDOB method that gets called whenever we click on the button ,remember we had set the button’s onClick attribute to sendDOB and now by defining this method we are telling what should happen when we click the button.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Intents

In the same way we created MainActivity which served as the main entry point for our app, we can create other activities too and the relationship between all these activities decides the app’s navigational pattern between different screens. So before coding an app, it is good to plan out the flow of the app and the different screens required beforehand and then create activities according to it.

An intent is a kind of object that serves to pass a message requesting an action to be performed by the same app or by a different app.

There are two types of intents

1. Implicit intents

These intents do not name any specific app component that should perform the requested action but instead declares a general action which allows the intent to be handled by other apps.

Eg.: Sending an email , even if our app can’t send an email we can declare an implicit intent requesting an email app from our phone to send the email.

2. Explicit intents

These intents specify which application will satisfy the intent, by giving either the target app’s package name or a fully-qualified component class name. We use an explicit intent to start a component in our own app, because we know the class name of the activity we want to start.

Eg.: Start a new activity within our own app in response to a user button click or any other event.

Declaring an intent to navigate from MainActivity to DetailsActivity when user clicks showBirthday button

  • Define sendDOB method outside of this method takes a view object as parameter. This view refers to the button which is clicked to invoke this method, so when we click the button, the view will hold a reference to that button and we can use that reference if we want to do any changes to the view.
  • We create an explicit intent that will help us launch the DetailsActivity which will open up a new screen and tell us our birthday. The intent takes the first parameter as the current context and send parameter as the name of the class that we want the intent to start.
  • We define an if-else check to see if the date is valid to be passed to the new screen.
  • If the DOB variable holds a null string then make a toast message on the screen asking user to input the correct birthday.
  • If not the date is valid and we are putting this date information inside the intent that we just created. The intent object can be thought of as a bag that can carry information to the new activity when it gets there. The first argument to putExtra is the key and the second argument is the value that we want to send.

Finally, we start the intent by startActivity (intent) which sends us to the Details Activity screen.

But this will not work yet as we are yet to define the DetailsActivity.

Let’s create a DetailsActivity

  • Goto File -> New -> Activity -> EmptyActivity a dialog box will popup.
  • Set the name to DetailsActivity and leave everything else as it is.
  • Click Finish

 

Create empty activity dialog

 

Now we get a new DetailsActivity.java file and an activity_details.xml file.

Lets define the layout for this file.

  • Goto app > res > layout > activity_details.xml
  • Add a RelativeLayout as the root viewgroup. Set the layout_width and layout_height attribute’s to Optionally set a left and right padding.
  • Add a TextView with a layout_width of match_parent and layout_height as wrap_content. Set its textSize to 20dp and gravity to center to center the text in the TextView. Also set the attribute layout_centerInParent to true center the TextView in the middle of the screen. Set the textAppearance to whatever looks good Give it an id to refer to it later.

This is how the xml file should look after all these changes are done.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Now let’s head over to DetailsActivity.java to set this TextView’s text dynamically.

  • Goto app > java > com.example.helloworld > DetailsActivity
  • Inside onCreate first find the id corresponding to the textview that we just created.
  • Also get the intent that begins this activity using the getIntent() method.

Intent intent = getIntent();

  • Extract the extra data from this intent object that we had passed from the MainActivity using getStringExtra method.The argument passed should match the name of the key we had used in putExtra method of MainActivity.

String dob=intent.getStringExtra(“dateOfBirth”); ·

  • From this dob string extract the year, month, and date, cast it to integer and store it in separate variables.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • Define two Calendar object instances at the top outside of on create and initialize them.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • Both myDOB and now hold the complete date and time information of whenever the object got initialized. Inside onCreate define three more int variables to store the current year, month and date and initialize them using the get method of the calendar.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • Set the myDOB calendatr instance to whatever year, month, day was passed on from the MainActivity and the now instance to the current year, month and date.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • Next we do an if-else check to see whether the date we got weas from the future.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

  • If it was not from the future we fetch the corresponding day from strDays array which we define at the top outside of onCreate and if the date was from the future we set a corresponding message in the textView.

Note:

  • we are subtracting one while indexing strDays, because DAY_OF_WEEK returns an int from 1 to 7 (1 indicates Sunday and 7 indicate Saturday) but our strDays array is 0-indexed.
  • Also while setting the month variable we subtract 1 because the the Calender class begins counting months from 0 (0 is January and 11 is December). Since we have the correct month we should subtract 1 from it to take it to the correct month of the Calendar class object.

This is how the DetailsActivity should finally look

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

There you go!

Now everything is ready and we can run and test our app.

 

App on startup

 

After inserting name

 

After inserting birthday

 

After hitting show birthday button

 

SEE ALL Add a note
YOU
Add your Comment

We would love to see what you build out of these learnings!

Click here to submit your projects, share it with the world and stand a chance to be rewarded.

top

Knowledge and Content by Li2 Technologies | © 2021 NASSCOM Foundation | All rights reserved

X