Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating our Android Application
2.1.
Opening up Android Studio
2.2.
Add an activity to Mobile
2.3.
Configuring your project configurations
2.4.
Writing code in the development environment
3.
Coding the Hello World App
3.1.
The Default Main Activity
3.1.1.
The Default Main Activity Java Code (MainActivity.java)
3.1.2.
The Default Layout XML File (activity_main.xml)
3.1.3.
Android Manifest File (AndroidManifest.xml)
3.2.
The Strings File
4.
Running the Application
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Android Hello World Application

Author Vasu Bansal
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

This blog will discuss programming with Android Framework and creating our first Hello World Application. The hello world program is the first and most basic program that we write when learning some new programming language or framework. 

For smooth development of Android applications, you need to set up an IDE like Android Studio along with the Android SDK. Feel free to refer to the blog Android Studio and Environment Setup on the Coding Ninjas Website to go over the details to set up your environment. We will walk over the steps to create our first Hello World Android application in the next section.

Creating our Android Application

The following are the steps to be followed to create your Android application. The order of steps may vary depending upon your version of Android Studio, but the steps remain the same in any release of this IDE.

Opening up Android Studio

The first step is to open up the Android Studio IDE. You can open the IDE by searching “Android Studio” in the start menu or simply clicking on the Desktop shortcut of the Android Studio.

The following window will open up once you open Android Studio. Press the New Project button at the top of the window to create a new Android Studio project.

Add an activity to Mobile

In the next step, Android Studio will ask you to select the device type, which is shown in the left half of the image shown below. You need to also choose the kind of activity based upon your requirements which is shown in the right half of the picture. In this tutorial, I have chosen Phone and Tablet as the device type and Basic Activity as the type of activity. Press the Next button at the end.

Configuring your project configurations

Add the name of your project in the Name field. In this blog, we create a project with the name Hello World. Configure the save location depending upon your local machine storage. After this, select your preferred language from the dropdown field. In this blog, I am choosing Java as the implementation language. In the end, you need to select the Minimum SDK version from the set of options under the dropdown field. In this blog, I have chosen Android 5.0 (Lollipop) as the minimum SDK version, which runs on 98% of the devices in use according to the estimates. Press the Finish button at the end.

Writing code in the development environment

This is the final screen that opens up after selecting all the project configurations. You can write all the code of your application here in this development area. To understand this newly created project's directory structure and app components, refer to the blog Android App Components and Folder Structure on the Coding Ninjas Website.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Coding the Hello World App

We successfully set up our project configuration in the last section and added the boilerplate code to our app. This section will go over the essential components of our Hello World application.

The Default Main Activity

The first screen that appears when you run your app is the main activity. Each activity represents a user interface panel in our Android app. There is an XML layout file and Java/Kotlin implementation file corresponding to each activity in our application.

Refer to the blog Android Activity and Types on our Coding Ninjas Website to learn more about Android activities.

The Default Main Activity Java Code (MainActivity.java)

A lot of boilerplate code will be generated by Android Studio. Do not get scared by seeing that code. The MainActivity.java file can be found under the directory app/java/com.example.helloworld. If you are following this blog and selected the same configurations as specified in the previous section, you will also see two more files other than the MainActivity.java file. They are namely FirstFragment.java and SecondFragment.java. We don’t need to do much in any of these files to create our Hello World application.

The following is the code of the MainActivity.java file.

Code:

package com.example.helloworld;

import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.helloworld.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

The most crucial method in this file is the onCreate method which is called when an activity is created. One can also notice that we are overriding this method as we extend this method from the AppCompatActivity class.

The Default Layout XML File (activity_main.xml)

The layouts of our application are defined in the XML files. These files are present in the directory app/res/layout. The name of the layout XML file represents the task that the file in question is performing. If you selected basic activity as the activity type in the previous section, you will also see three more files other than the activity_main.xml file. They are namely content_main.xml, fragment_first.xml and fragment_second.xml. The following is the code of the activity_main.xml file.

Code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.HelloWorld.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/Theme.HelloWorld.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="@dimen/fab_margin"
        android:layout_marginBottom="16dp"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Note: The @string in the XML files refer to the strings.xml file in the directory app/res/values. We will study more about the strings.xml in the later sections of this blog.

Android Manifest File (AndroidManifest.xml)

In most cases, our application will have numerous activities, which must be described in the AndroidManifest.xml file. The MAIN action and LAUNCHER category elements in intent filters (<intent-filter>) must be used in our manifest file to specify the main activity of our app. Our app icon will not appear on the home screen's list of apps if we do not provide the MAIN action or LAUNCHER category for the main activity.

The default code for the AndroidManifest.xml file generated by our Hello World app is shown below.

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworld">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.HelloWorld">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.HelloWorld.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The Strings File

The strings.xml file, which is present in the directory app/res/values, includes all of the text that your app utilises. All important strings like default text and names of buttons are stored in this file. The following code is present in the strings.xml file created using the project configurations specified in the previous section.

Code:

<resources>
    <string name="app_name">Hello World</string>
    <string name="action_settings">Settings</string>
    <!-- Strings used for fragments for navigation -->
    <string name="first_fragment_label">First Fragment</string>
    <string name="second_fragment_label">Second Fragment</string>
    <string name="next">Next</string>
    <string name="previous">Previous</string>

    <string name="hello_first_fragment">Hello first fragment</string>
    <string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string>
</resources>

To create your application into Hello World Application, just change the following line in this file. 

<string name="hello_first_fragment">Hello first fragment</string>

// change the above line to the following line

<string name="hello_first_fragment">Hello World !!!</string>

If you have successfully reached here following all the instructions, you have created your Hello World application. In the next step, we will see how to run this application.

Running the Application

To run your android application, you need to first create an AVD (Android Virtual Device). In this blog, I have selected Pixel 2 as the AVD. You may choose the AVD of your choice. After that, simply press the run app button at the top right corner of your Android Studio window, as shown in the image below. 


 

The following is the output that you will see after running your application.


FAQs

  1. Are XML files sensitive to indentation?
    No, XML files are not sensitive to indentation.
     
  2. Which is the latest android version?
    The latest Android version is Android 12 and was released in Oct 2021.
     
  3. What is the hardware profile of AVD?
    The hardware profile describes a device's attributes as it leaves the factory. Certain hardware profiles, such as Pixel devices, are preloaded in the Device Manager, and you can define or edit them as needed. 

Key Takeaways

Cheers if you reached here!! This blog aimed to introduce you to the Android framework and create your first Hello World Application. To read more about Android resources and building blocks, refer to this blog on the Coding Ninjas website.

Yet there is never an end to the learning process, so check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development and how to design the applications of future. Until then, good luck!!

Live masterclass