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

Android Programming Lab

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)
1 views12 pages

Android Programming Lab

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
You are on page 1/ 12

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 (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.
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:
The following is the code of the MainActivity.java file.
<?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.
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: com.example.myfirsttoastapp (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 AndroidManifest.xml, which describes the fundamental


characteristics of your app and defines its components.

o java: Contains your Java source code files.

 com.example.myfirsttoastapp (or your package name): This is where your


MainActivity.java 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.

 colors.xml

 strings.xml

 themes.xml

 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 (MainActivity.java)

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 MainActivity.java: Navigate to app > res > java > com.example.myfirsttoastapp (your
package name) and double-click MainActivity.java.

2. Modify the MainActivity.java file:

Replace the existing content in MainActivity.java 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: com.example.factorialcalculator (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 (MainActivity.java)
Now, let's implement the logic to handle input, calculate the factorial, and display the Toast.
1. Open MainActivity.java: Navigate to app > res > java > com.example.factorialcalculator (your
package name) and double-click MainActivity.java.
2. Modify the MainActivity.java 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.

You might also like