0% found this document useful (0 votes)
131 views12 pages

Android Hello World App Tutorial

The document provides a step-by-step guide to creating two Android applications: a 'Hello World' app and a toast message app. It outlines the process of setting up a project in Android Studio, configuring project settings, writing necessary Java code, and designing the user interface using XML. Additionally, it explains how to run the applications on an Android emulator or physical device.

Uploaded by

Raja Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views12 pages

Android Hello World App Tutorial

The document provides a step-by-step guide to creating two Android applications: a 'Hello World' app and a toast message app. It outlines the process of setting up a project in Android Studio, configuring project settings, writing necessary Java code, and designing the user interface using XML. Additionally, it explains how to run the applications on an Android emulator or physical device.

Uploaded by

Raja Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Android programming Lab

List of Exercises:
1) Create an Android Application To display “Hello World”

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

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.
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.
The Default Main Activity Java Code ([Link])
A lot of boilerplate code will be generated by Android Studio. Do not get scared by seeing that code.
The [Link] file can be found under the directory app/java/[Link]. 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 [Link] file. They are
namely [Link] and [Link]. We don’t need to do much in any of these
files to create our Hello World application.
Code:
package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private AppBarConfiguration appBarConfiguration;


private ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);

binding = [Link](getLayoutInflater());
setContentView([Link]());

setSupportActionBar([Link]);

NavController navController = [Link](this, [Link].nav_host_fragment_content_


main);
appBarConfiguration = new [Link]([Link]()).build();
[Link](this, navController, appBarConfiguration);

[Link](new [Link]() {
@Override
public void onClick(View view) {
[Link](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([Link].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 [Link].
int id = [Link]();
//noinspection SimplifiableIfStatement
if (id == [Link].action_settings) {
return true;
}

return [Link](item);
}

@Override
public boolean onSupportNavigateUp() {

NavController navController = [Link](this, [Link].nav_host_fragment_content_


main);
return [Link](navController, appBarConfiguration)
|| [Link]();
}
}
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:
The following is the code of the [Link] file.
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="http://
[Link]/apk/res/android"
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<[Link]
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/[Link]">

<[Link]
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/[Link]" />

</[Link]>

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

<[Link]
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" />

</[Link]>
Note: The @string in the XML files refer to the [Link] file in the directory app/res/values. We
will study more about the [Link] in the later sections of this blog.
Android Manifest File ([Link])
In most cases, our application will have numerous activities, which must be described in
the [Link] 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 [Link] file generated by our Hello World app is shown below.
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]">

<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/[Link]">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/[Link]">
<intent-filter>
<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>
</activity>
</application>

</manifest>
The Strings File
The [Link] 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 [Link] 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.
Exercise-2 create an android app to show toast message as
hello world
What is a Toast Message?

A Toast message is a brief message that appears on the screen for a short period and then disappears
automatically. It's commonly used for notifications or confirmations that don't require user
interaction.

Prerequisites:

 Android Studio installed on your computer.

 Basic understanding of Java programming.

Step 1: Create a New Android Studio Project

1. Open Android Studio: Launch Android Studio.

2. Start a New Project:

o If you're on the welcome screen, click "New Project".

o If you already have a project open, go to File > New > New Project....

3. Choose a Project Template:

o Select the "Phone and Tablet" tab.

o Choose "Empty Views Activity" (or "Empty Activity" for older versions of Android
Studio). This template provides a basic activity with a layout file.

o Click "Next".

4. Configure Your Project:

o Name: MyFirstToastApp (or any name you prefer)

o Package name: [Link] (Android Studio will auto-generate this


based on your name, usually fine to keep as default)

o Save location: Choose a directory on your computer where you want to save your
project.

o Language: Select Java.

o Minimum SDK: Choose API 21: Android 5.0 (Lollipop). This ensures your app runs on
a wide range of devices.

o Click "Finish".

Android Studio will now create your project, which might take a few moments as it sets up the
necessary files and downloads dependencies.
Step 2: Understand the Project Structure

Once the project is created, you'll see the project structure in the "Project" window (usually on the
left side). Key directories and files include:

 app folder: Contains all the code, resources, and assets for your app.

o manifests: Contains [Link], which describes the fundamental


characteristics of your app and defines its components.

o java: Contains your Java source code files.

 [Link] (or your package name): This is where your


[Link] file is located.

o res (resources): Contains all non-code resources like layouts, images, strings, etc.

 drawable: For images and custom shapes.

 layout: Contains XML layout files that define your app's user interface. You'll
find activity_main.xml here.

 mipmap: For launcher icons.

 values: For defining colors, strings, and styles.

 [Link]

 [Link]

 [Link]

 Gradle Scripts: Contains files related to Gradle, the build system used by Android Studio.

Step 3: Design the User Interface (activity_main.xml)

We'll add a simple button to the layout. When this button is clicked, our Toast message will appear.

1. Open activity_main.xml: Navigate to app > res > layout and double-click activity_main.xml.

2. Switch to Design View (or Split View): At the top right of the design editor, you'll see "Code",
"Split", and "Design" tabs. Click "Split" to see both the design preview and the XML code
simultaneously, or "Code" to edit the XML directly.

3. Modify the XML Layout:

o By default, the "Empty Views Activity" template includes a TextView with "Hello
World!". You can delete this TextView.

o Add a Button element inside the ConstraintLayout.

Replace the existing content in activity_main.xml with the following code.

Step 4: Write the Java Code ([Link])

Now, we'll write the Java code to find the button, set up a listener for its clicks, and display the Toast
message.
1. Open [Link]: Navigate to app > res > java > [Link] (your
package name) and double-click [Link].

2. Modify the [Link] file:

Replace the existing content in [Link] with the following code.

Step 5: Run Your App

You can run your app on an Android Emulator or a physical Android device.

Option A: Run on an Android Emulator

1. Create an AVD (Android Virtual Device) if you don't have one:

o Go to Tools > Device Manager (or AVD Manager in older versions).

o Click "Create device".

o Choose a device definition (e.g., "Pixel 5"). Click "Next".

o Select a system image (e.g., "API 30" or "API 33"). If you don't have one downloaded,
click the "Download" icon next to it. Click "Next".

o Give your AVD a name and click "Finish".

2. Run the App:

o In the Android Studio toolbar, select your desired AVD from the dropdown menu
(e.g., "Pixel 5 API 30").

o Click the green "Run 'app'" button (a green triangle icon).

o Android Studio will build your app and launch it on the selected emulator.

Option B: Run on a Physical Android Device

1. Enable USB Debugging on your device:

o Go to your device's Settings > About phone.

o Tap "Build number" seven times rapidly to enable "Developer options".

o Go back to Settings > System > Developer options (or similar path, depending on
your Android version).

o Enable "USB debugging".

2. Connect your device: Connect your Android device to your computer using a USB cable.

3. Allow USB Debugging: On your device, a dialog might pop up asking to "Allow USB
debugging". Tap "OK".

4. Run the App:

o In the Android Studio toolbar, your connected device should appear in the dropdown
menu. Select it.

o Click the green "Run 'app'" button.


o Android Studio will install and launch your app on your device.

Step 6: Test Your App

Once the app launches on the emulator or device, you should see a screen with a single button
labeled "Show Toast".

1. Tap the "Show Toast" button.

2. You should see a small "Hello World!" message briefly appear at the bottom of the screen
and then fade away.

Exercise-3
Create an Android app to accept a number in text field and
display the factorial of it in a Toast message on clicking a
button
Prerequisites:
 Android Studio installed and set up.
 Basic understanding of Java programming and the previous "Hello World" Toast app.
Step 1: Create a New Android Studio Project
1. Open Android Studio.
2. Start a New Project:
o Click "New Project" from the welcome screen or go to File > New > New Project....
3. Choose a Project Template:
o Select "Phone and Tablet" tab.
o Choose "Empty Views Activity" (or "Empty Activity").
o Click "Next".
4. Configure Your Project:
o Name: FactorialCalculator
o Package name: [Link] (default is usually fine)
o Save location: Your preferred directory.
o Language: Java.
o Minimum SDK: API 21: Android 5.0 (Lollipop).
o Click "Finish".
Wait for Android Studio to set up your new project.
Step 2: Design the User Interface (activity_main.xml)
We need an EditText for the user to type in a number, a Button to trigger the calculation, and a
TextView to display the result (in addition to the Toast).
1. Open activity_main.xml: Navigate to app > res > layout and double-click activity_main.xml.
2. Switch to Split View (or Code View): Click the "Split" tab at the top right of the design editor.
3. Modify the XML Layout:
o Remove the default TextView if it exists.
o Add an EditText, a Button, and a TextView.
Step 3: Write the Java Code ([Link])
Now, let's implement the logic to handle input, calculate the factorial, and display the Toast.
1. Open [Link]: Navigate to app > res > java > [Link] (your
package name) and double-click [Link].
2. Modify the [Link] file:
Step 4: Run Your App
You can run your app on an Android Emulator or a physical Android device.
Option A: Run on an Android Emulator
1. Ensure you have an AVD (Android Virtual Device) set up. If not, create one via Tools >
Device Manager.
2. Select your AVD from the dropdown menu in the Android Studio toolbar.
3. Click the green "Run 'app'" button (triangle icon).
Option B: Run on a Physical Android Device
1. Enable USB Debugging on your device (Settings > About phone > tap "Build number" 7 times
> Developer options > "USB debugging").
2. Connect your device to your computer via USB.
3. Allow USB Debugging on your device if prompted.
4. Select your device from the dropdown menu in Android Studio.
5. Click the green "Run 'app'" button.
Step 5: Test Your App
Once the app launches on the emulator or device:
1. Enter a number (e.g., 5) into the "Enter a non-negative number" field.
2. Tap the "Calculate Factorial" button.
3. You should see a Toast message pop up at the bottom of the screen saying "Factorial of 5 is
120".
4. The TextView below the button should also update to "Factorial of 5 is 120".
5. Test invalid inputs:
o Try entering a negative number (e.g., -3). You should get a Toast: "Please enter a non-
negative number."
o Try entering text (e.g., hello). You should get a Toast: "Invalid input. Please enter a valid
number."
o Try entering a large number (e.g., 25). You should get a Toast: "Number too large for
exact calculation (max 20)."
This exercise demonstrates how to build a simple interactive app with input validation and
calculation.

Common questions

Powered by AI

Specifying the MAIN action and LAUNCHER category in the AndroidManifest.xml file is crucial because they define the main activity that should start when the application is launched. Without these declarations, the app icon will not appear on the home screen's list of apps, rendering it inaccessible for users to start the application directly .

Handling user input validation in an Android app for factorial calculation involves several checks in 'MainActivity.java'. First, retrieve and parse the user input from an EditText. Use try-catch blocks or regex to verify that the input is a valid non-negative integer. Display a Toast message if input is invalid or exceeds calculation limits. Implement error handling for non-numerical inputs and use constraints defined in XML or programmatically to guide user interactions and prevent errors .

The strings.xml file is crucial in Android applications as it centralizes all the text used throughout the app. This includes interface text, button labels, and other strings, allowing for easy modifications. It aids in internationalization by facilitating the translation of the app into multiple languages without altering the code. Maintaining text separate from code also follows best practices for resource management and reduces chances of introducing errors during updates .

The 'activity_main.xml' file defines the layout of the main user interface in an Android application. It specifies the arrangement of UI components within a 'CoordinatorLayout,' including app bars, toolbars, and any included layouts such as 'content_main.xml'. Components like FloatingActionButton are defined here as well. The file ensures that the visual structure aligns with the application's functional requirements .

The purpose of an AVD in Android development is to simulate an Android device for testing and running applications without needing physical hardware. It allows developers to emulate devices with different configurations, screen sizes, and SDK levels to ensure app compatibility and functionality across a range of Android environments .

To add a Button to 'activity_main.xml', open the file and add a Button element within the layout, setting its attributes like width, height, and text. In 'MainActivity.java', retrieve the button reference using findViewById, and set an OnClickListener on it. Inside the onClick method, create a Toast message using Toast.makeText, specifying the context, message, and duration, and call show() to display the message upon button click .

To create an Android application that shows a Toast message, start a new project in Android Studio with 'Empty Views Activity' and set up the UI to include a Button in 'activity_main.xml'. In 'MainActivity.java', find the button using findViewById, set an OnClickListener on it, and within the listener, instantiate a Toast using Toast.makeText and call show() to display it .

The NavController in Android applications is significant for navigating between destinations defined in a navigation graph. It manages navigation within the app's activity, handling transactions between fragments and ensuring a smooth and efficient UI flow. It allows developers to define navigation actions and arguments, promoting a consistent navigation experience across different app components .

Overriding the onCreate method in MainActivity.java is significant because it is responsible for initializing the activity. It sets up the user interface using setContentView and binds data components if necessary. This method is inherited from AppCompatActivity and is called when the activity is created, serving as the entry point for further customizations in the app's initial setup .

To configure a new project for a "Hello World" application, open Android Studio and create a new project by selecting 'Phone and Tablet' as the device type and 'Basic Activity' as the activity type. Name the project 'Hello World,' select Java as the programming language, and choose Android 5.0 (Lollipop) as the minimum SDK version. Once the project is set up, write the code for the 'MainActivity.java' and the XML layout files.

You might also like