0% found this document useful (0 votes)
3 views56 pages

Android Studio - LAB Guide

This document is a lab guide for creating Android applications using Android Studio, detailing the setup of project files, configuration of an Android Virtual Device (AVD), and execution of sample programs. It includes instructions for building basic applications such as a 'Hello World' app, handling screen orientation, creating a login interface, and demonstrating explicit and implicit intents. Each program is accompanied by specific code snippets and XML layouts to facilitate the development process.

Uploaded by

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

Android Studio - LAB Guide

This document is a lab guide for creating Android applications using Android Studio, detailing the setup of project files, configuration of an Android Virtual Device (AVD), and execution of sample programs. It includes instructions for building basic applications such as a 'Hello World' app, handling screen orientation, creating a login interface, and demonstrating explicit and implicit intents. Each program is accompanied by specific code snippets and XML layouts to facilitate the development process.

Uploaded by

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

Android Studio: LAB Guide

Welcome to your first Android Application lab!

Part 1: Finding Your Files (The Project Explorer)


When you initialize a new Android Studio project using the "New Empty Views Activity"
template, the environment automatically generates a complex hierarchy of folders and
configuration files. While this structure is extensive, the majority of your development
time will be focused on just two critical files.

To efficiently locate these files, direct your attention to the Project panel, situated on the
far left of the Android Studio interface. Crucially, ensure the view setting is configured
correctly: at the top of this panel, use the dropdown menu to select the "Android" view.
This setting filters the complex file system into a more logical, app-centric hierarchy.1.
The Java File (The Application Logic)

This file is the core of your application's behavior. It dictates what your app does—it
contains the instructions for handling user interactions, performing complex calculations,
fetching or saving data from a database, and managing the overall state of the application.

●​ Primary Function: Contains the Kotlin or Java code responsible for the app's
functionality.
●​ Default Path: app > java > [Link] > [Link] (The
[Link] folder will be uniquely named based on the domain you entered
during project creation).
●​ Important Note: Within the java directory, you will typically find three sub-folders.
Always use the first package folder, which contains your main application code.
Completely disregard and ignore the folders labeled (androidTest) and (test), as these are
designated for automated testing and are not where you will write your core app logic.

2. The XML File (The User Interface Design)

This file defines the visual layout and structure of your app's user interface (UI). It
governs how your app looks—it is where you place UI components such as buttons, text
input fields (EditText), labels (TextView), images (ImageView), and define their colors,
sizes, and positioning.
●​ Primary Function: Contains the Extensible Markup Language (XML) code that
structures and styles the visual elements presented to the user.
●​ Default Path: app > res > layout > activity_main.xml
○​ The res (resources) folder holds all non-code assets, including layouts, images
(drawable), application icons (mipmap), and defined colors/strings (values).
○​ The layout folder is specifically for the XML files that define the screen structure.

Part 2: Configuring the Android Virtual Device (AVD)


To test and run your application, you need a mobile environment. While you can connect
a physical Android device, the recommended approach for development is to use an
Android Virtual Device (AVD), commonly known as an emulator, which runs directly on
your computer.

1.​ Access the Device Manager: Locate the toolbar at the top right of the Android Studio
window. Click the icon that represents a mobile phone adjacent to a small Android logo.
This action will open the Device Manager window.
2.​ Initiate New Device Creation: Within the Device Manager, select the Create Device
button to begin the setup process for a new virtual phone.
3.​ Choose Hardware Profile: On the first configuration screen, you must select the
physical characteristics of your virtual device. For a standard development experience,
choose a widely-used phone model from the "Phone" category, such as the Pixel 6. After
making your selection, click Next.
4.​ Select a System Image (OS): The system image is the operating system (OS) that your
virtual phone will run. It corresponds to a specific Android API level. To ensure
compatibility with the current lab exercises, locate and select the system image for
Nougat (API Level 24). If the image is not already downloaded, an accompanying
"Download" link will be visible. Click this link and wait for the OS image to download
completely. Once the download is finished, select the image from the list and proceed by
clicking Next.
5.​ Finalize the AVD Setup: The final configuration screen allows for advanced settings
(like performance and orientation), but for initial setup, the default values are entirely
adequate. Review the configuration, and then click Finish to create and save your new
AVD.
Part 3: Executing Your Program and Testing
With your application code written and your virtual testing environment established, you
are ready to compile and run your app.

1.​ Launch the Emulator: Return to the Device Manager. Find your newly created virtual
device and click the Play (Triangle) button next to its name. This initiates the boot-up
process for the virtual phone, which may take up to a couple of minutes. The emulator
will open in its own dedicated window.
2.​ Verify Target Device Selection: Look at the main toolbar near the top of the Android
Studio IDE. There is a dropdown menu that displays the currently selected device. Ensure
your newly launched virtual device (e.g., "Pixel 6 API 24") is selected in this dropdown.
3.​ Execute the Build and Run Command: Click the prominent green Run 'app' button,
which typically resembles a play icon. Alternatively, you can use the keyboard shortcut
Shift + F10 (common on Windows/Linux) to start the process.
4.​ Monitor the Build Status: Pay attention to the status bar at the bottom of the Android
Studio window. This area displays the output of Gradle, the automated build system used
by Android. Once Gradle successfully completes the compilation and packaging of your
application, your app will be automatically installed and launched on the virtual
phone/emulator window!
Program 1: Creating a "Hello World" Application
Objective: Build a foundational Android application that displays text on the screen.

Instructions for Execution:


1.​ Open Android Studio and click New Project.
2.​ Choose Empty Views Activity and click Next.
3.​ Set the Name to HelloWorld, Language to Java, and Minimum SDK to API 24
("Nougat"), then click Finish.
4.​ Navigate to app/src/main/res/layout/activity_main.xml. Replace the existing code with
the XML code provided below to design the screen.
5.​ Navigate to app/src/main/java/com/yourpackage/helloworld/[Link]. Ensure
your package name matches, then update the code inside to match the Java code provided
below.
6.​ Click the green Run 'app' button (or press Shift + F10) to execute the program on your
emulator.

Code Files:
1. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</[Link]>
2. [Link]

Java:
package [Link]; // IMPORTANT: Change this to match your actual package name

import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}

Program 2: Screen Orientation and Explicit Intents


Objective: Create an application that displays different messages based on the screen orientation
by launching a second activity.

Instructions for Execution:


1.​ Create a new project (Empty Views Activity, Java, API 24) named ScreenOrientation.
2.​ Create a second screen: Right-click the app folder -> New -> Activity -> Empty Views
Activity. Name it MainActivity2 and click Finish.
3.​ Update activity_main.xml and activity_main2.xml with the provided layout code.
4.​ Update [Link] and [Link] with the provided logic.
5.​ Crucial Step: Navigate to app/src/main/[Link]. You must lock the
orientations here for the activities to work correctly.
6.​ Run the app (Shift + F10).

Code Files:
1. [Link] (Modify the <activity> tags inside your application block)

XML
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>

<activity
android:name=".MainActivity2"
android:exported="false"
android:screenOrientation="landscape" />

2. activity_main.xml (Portrait Layout)

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This activity is in Portrait orientation"
android:textSize="22sp"
android:textAlignment="center"
android:layout_marginBottom="30dp"/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Next Activity"
android:onClick="onClick" />

</LinearLayout>
3. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}

public void onClick(View v) {


Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
}

4. activity_main2.xml (Landscape Layout)

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Landscape orientation"
android:textSize="22sp" />

</LinearLayout>
5. [Link]

Java
package [Link]; // Change to your package name

import [Link];
import [Link];

public class MainActivity2 extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main2);
}
}
Program 3: Creating a Custom Login Window
Objective: Develop a login interface using UI controls and custom drawable backgrounds.
Validate a hardcoded username and password.

Instructions for Execution:


1.​ Create a new project (Empty Views Activity, Java, API 24) named LoginWindow.
2.​ Create Background Shapes: * Navigate to app/src/main/res/drawable. Right-click
drawable -> New -> Drawable Resource File.
○​ Name the first file bg_outer.xml, change the root element to shape, and click OK.
Paste the provided code.
○​ Repeat this process to create a second file named bg_inner.xml.
3.​ Update activity_main.xml to build the UI with these new backgrounds.
4.​ Update [Link] to handle the button click and validate the login credentials
using Toast messages.
5.​ Run the app (Shift + F10).

Code Files:
1. bg_outer.xml (Drawable Resource)

XML
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="[Link]
<corners android:radius="12dp"/>
<gradient
android:startColor="#B388FF"
android:endColor="#397C9A"
android:angle="100"/>
</shape>

2. bg_inner.xml (Drawable Resource)

XML
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="[Link]
<gradient
android:startColor="#84FFFF"
android:endColor="#FF0088"
android:angle="100"/>
<corners android:radius="20dp"/>
</shape>
3. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_outer"
android:padding="20dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/bg_inner"
android:gravity="center"
android:orientation="vertical"
android:padding="30dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="Login Page"
android:textColor="@android:color/black"
android:textSize="32sp"
android:textStyle="bold" />

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:hint="Username"
android:inputType="text"/>

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:hint="Password"
android:inputType="textPassword" />

<Button
android:id="@+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login" />

</LinearLayout>
</RelativeLayout>

4. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {

private EditText editTextUsername, editTextPassword;


private Button buttonLogin;

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

editTextUsername = findViewById([Link]);
editTextPassword = findViewById([Link]);
buttonLogin = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
String username = [Link]().toString().trim();
String password = [Link]().toString().trim();
// Validation check as requested in the manual
if ([Link]("admin") && [Link]("pass")) {
[Link]([Link], "Login successful",
Toast.LENGTH_SHORT).show();
} else {
[Link]([Link], "Invalid username or password",
Toast.LENGTH_SHORT).show();
}
}
});
}
}

Program 4: Explicit and Implicit Intents


Objective: Create an application demonstrating how to open a new screen inside the app
(Explicit Intent) and how to open a web browser outside the app (Implicit Intent).

Instructions for Execution:

1.​ Create a new project named IntentApp (Empty Views Activity, Java, API 24).
2.​ Create the second screen: Right-click the app folder -> New -> Activity -> Empty Views
Activity. Name it NewActivity and click Finish.
3.​ Update activity_main.xml with the two buttons.
4.​ Update [Link] with the Intent logic.
5.​ Update activity_new.xml to design the second screen.
6.​ Run the app (Shift + F10).

Code Files:

1. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp">
<Button
android:id="@+id/btnExplicit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Explicit Intent"
android:onClick="onExplicitButtonClicked"
android:layout_marginBottom="20dp"/>

<Button
android:id="@+id/btnImplicit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Implicit Intent"
android:onClick="onImplicitButtonClicked" />

</LinearLayout>

2. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}

// Opens a new Activity within your app (Explicit)


public void onExplicitButtonClicked(View view) {
Intent i = new Intent([Link], [Link]);
startActivity(i);
}

// Opens a URL in the phone's web browser (Implicit)


public void onImplicitButtonClicked(View view) {
Uri url = [Link]("[Link]
Intent i = new Intent(Intent.ACTION_VIEW, url);
startActivity(i);
}
}

3. activity_new.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the New Activity!"
android:textSize="24sp"
android:textStyle="bold"/>

</LinearLayout>

Program 5: Custom Opening Screen (Splash Screen)


Objective: Create a splash screen that displays a logo for a few seconds before automatically
transitioning to the main home screen.
Note for Students: The original manual uses a custom image (@drawable/img). Since you don't
have that file, this version uses the default Android launcher icon so the app won't crash.

Instructions for Execution:

1.​ Create a new project named SplashScreenApp (Empty Views Activity, Java, API 24).
2.​ Create the home screen: Right-click the app folder -> New -> Activity -> Empty Views
Activity. Name it Mainscreen and click Finish.
3.​ Update activity_main.xml (the Splash Screen design) and [Link] (the timer
logic).
4.​ Update activity_mainscreen.xml (the Home Screen design).
5.​ Run the app (Shift + F10).
Code Files:

1. activity_main.xml (The Splash Screen)

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#E0F7FA">

<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher" /> </RelativeLayout>

2. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {

private static final int SPLASH_SCREEN_TIME_OUT = 3000; // 3 seconds is standard, 10 is


too long

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

// Makes the splash screen full screen


getWindow().setFlags([Link].FLAG_FULLSCREEN,
[Link].FLAG_FULLSCREEN);

setContentView([Link].activity_main);
// Delays the transition to the next screen
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent([Link], [Link]);
startActivity(i);
finish(); // Prevents the user from hitting 'back' to return to the splash screen
}
}, SPLASH_SCREEN_TIME_OUT);
}
}

3. activity_mainscreen.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#FFF9C4">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Home Page"
android:textSize="32sp"
android:textStyle="bold"
android:textColor="@android:color/black"/>

</RelativeLayout>
Program 6: UI with All Views
Objective: Create a comprehensive user information form utilizing EditText, ToggleButton,
RadioGroup, Spinner, and a submit Button.

Note for Students: The original manual had several broken layout heights (like 40 p) which have
been corrected to 40dp here to ensure it compiles.

Instructions for Execution:

1.​ Create a new project named AllViewsUI (Empty Views Activity, Java, API 24).
2.​ Right-click the app/src/main/res/drawable folder -> New -> Drawable Resource File.
Name it [Link]. (We will use this single background to keep things clean and prevent
errors).
3.​ Update [Link] with the shape code below.
4.​ Update activity_main.xml to build the large form.
5.​ Update [Link] to populate the Spinner dropdown and handle the submit
button.
6.​ Run the app (Shift + F10).

Code Files:

1. [Link] (Drawable Resource)

XML
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="[Link]
<solid android:color="#E8F5E9"/>
<corners android:radius="15dp" />
<stroke android:color="#4CAF50" android:width="2dp"/>
</shape>

2. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center_horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Information"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#3F51B5"
android:layout_marginBottom="10dp"/>

<ToggleButton
android:id="@+id/toggleStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Active"
android:textOff="Inactive"
android:layout_marginBottom="20dp"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/bg"
android:padding="15dp">

<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="60dp"
android:hint="Full Name"
android:layout_marginBottom="10dp"/>

<EditText
android:id="@+id/editEmail"
android:layout_width="match_parent"
android:layout_height="60dp"
android:hint="Email Address"
android:inputType="textEmailAddress"
android:layout_marginBottom="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender:"
android:textSize="18sp"
android:textStyle="bold"/>

<RadioGroup
android:id="@+id/radioGroupGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10dp">

<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />

<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Country:"
android:textSize="18sp"
android:textStyle="bold"/>

<Spinner
android:id="@+id/spinnerCountry"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="20dp"/>

<Button
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit Form"
android:textSize="18sp"/>

</LinearLayout>
</LinearLayout>
</ScrollView>

3. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {

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

// Setup the Dropdown (Spinner)


Spinner spinner = findViewById([Link]);
String[] countries = {"India", "Pakistan", "China", "America", "England"}; [cite: 916, 917]
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
[Link].simple_spinner_item, countries);
[Link]([Link].simple_spinner_dropdown_item);
[Link](adapter);

// Setup the Submit Button


Button btnSubmit = findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
// Show a dialog box upon submission
[Link] builder = new [Link]([Link]);
[Link]("User Information"); [cite: 928]
[Link]("Successfully completed!"); [cite: 929, 930]
[Link]("OK", new [Link]() {
@Override
public void onClick(DialogInterface dialog, int which) {
[Link]();
}
});
[Link]();
}
});
}
}
Program 7: Creating an Options Menu
Objective: Create a standard menu in the application.

Note for Students: The original manual used a non-standard method to build the menu. We will
use the standard onCreateOptionsMenu method here, which is the industry best practice.

Instructions for Execution:

1.​ Create a new project named MenuApp (Empty Views Activity, Java, API 24).
2.​ Create the Menu Resource: * Right-click the app/src/main/res folder -> New ->
Android Resource Directory.
○​ Select menu from the Resource type dropdown and click OK.
○​ Right-click the new menu folder -> New -> Menu Resource File. Name it
[Link] and paste the provided code.
3.​ Update [Link] to inflate the menu and handle clicks. (You do not need to
change activity_main.xml for this program).
4.​ Run the app (Shift + F10). Look for the three dots in the top right corner of the app.

Code Files:

1. [Link] (Menu Resource)

XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
xmlns:app="[Link]

<item
android:id="@+id/php"
android:title="PHP"
app:showAsAction="never"/>

<item
android:id="@+id/java"
android:title="JAVA"
app:showAsAction="never"/>

<item
android:id="@+id/csharp"
android:title="C#"
app:showAsAction="never"/>
</menu>
2. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link], menu);
return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = [Link]();

if (id == [Link]) {
[Link](this, "PHP Page Selected", Toast.LENGTH_SHORT).show();
return true;
} else if (id == [Link]) {
[Link](this, "JAVA Page Selected", Toast.LENGTH_SHORT).show();
return true;
} else if (id == [Link]) {
[Link](this, "C# Page Selected", Toast.LENGTH_SHORT).show();
return true;
}

return [Link](item);
}}
Program 8: Read/Write Local Data (SharedPreferences)
Objective: Save simple data (like a username and password) to the device's local storage and
retrieve it on a different screen.

Instructions for Execution:

1.​ Create a new project named LocalDataApp (Empty Views Activity, Java, API 24).
2.​ Create a second screen: Right-click the app folder -> New -> Activity -> Empty Views
Activity. Name it MainActivity2 and click Finish.
3.​ Update activity_main.xml (The Save screen) and [Link] (Logic to write data).
4.​ Update activity_main2.xml (The Fetch screen) and [Link] (Logic to read
data).
5.​ Run the app (Shift + F10).

Code Files:

1. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Name:" />

<EditText
android:id="@+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Password:" />
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_marginBottom="20dp"/>

<Button
android:id="@+id/btnsave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Data" />

<Button
android:id="@+id/btnnext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Next Screen" />

</LinearLayout>

2. [Link]

Java
package [Link]; // Change to your package name

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

public class MainActivity extends AppCompatActivity {

EditText etUserName, etPassword;


Button btnsave, btnnext;

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

etUserName = findViewById([Link]);
etPassword = findViewById([Link]);
btnsave = findViewById([Link]);
btnnext = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View view) {
// Writing data to SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
[Link] editor = [Link]();

[Link]("username", [Link]().toString());
[Link]("password", [Link]().toString());
[Link](); // Saves the data asynchronously

[Link](getApplicationContext(), "Saved successfully",


Toast.LENGTH_SHORT).show();
}
});

[Link](new [Link]() {
@Override
public void onClick(View view) {
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
});
}
}

3. activity_main2.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<Button
android:id="@+id/btnFetch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch Saved Data"
android:layout_marginBottom="20dp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetched User Name:" />

<EditText
android:id="@+id/etFetchedUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:layout_marginBottom="20dp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetched Password:" />

<EditText
android:id="@+id/etFetchedPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false" />
</LinearLayout>

4. [Link]

Java
package [Link]; // Change to your package name

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity2 extends AppCompatActivity {

Button btnFetch;
EditText etFetchedUserName, etFetchedPassword;

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

btnFetch = findViewById([Link]);
etFetchedUserName = findViewById([Link]);
etFetchedPassword = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View view) {
// Reading data from SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);

// The second parameter is the default value if nothing is found


String username = [Link]("username", "No Name Found");
String password = [Link]("password", "No Password Found");

[Link](username);
[Link](password);
}
});
}
}
Program 9: Create / Read / Write with Database (SQLite)
Objective: Build a complete CRUD (Create, Read, Update, Delete) application using Android's
built-in SQLite database.

Instructions for Execution:

1.​ Create a new project named SQLiteApp (Empty Views Activity, Java, API 24).
2.​ Create two new Activities: Right-click the app folder -> New -> Activity -> Empty
Views Activity.
○​ Name the first one ViewActivity.
○​ Name the second one EditActivity.
3.​ Create a helper class: Right-click your Java package folder -> New -> Java Class. Name
it Student.
4.​ Replace the code in the seven files below carefully.
5.​ Run the app (Shift + F10). Add a student, click View, click on the student in the list, and
try editing or deleting them.

Code Files:

1. [Link] (Data Model)

Java
package [Link]; // Change to your package name

public class Student {


String id;
String name;
String course;
String fee;
}

2. activity_main.xml (Insert Screen)

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Course Registration"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginBottom="20dp"/>

<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />

<EditText
android:id="@+id/course"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Course" />

<EditText
android:id="@+id/fee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Fee"
android:inputType="number"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">

<Button
android:id="@+id/btInsert"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Insert" />

<Button
android:id="@+id/btView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="View All" />
</LinearLayout>

</LinearLayout>

3. [Link]

Java
package [Link]; // Change to your package name

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 {


EditText edName, edCourse, edFee;
Button btnInsert, btnView;

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

edName = findViewById([Link]);
edCourse = findViewById([Link]);
edFee = findViewById([Link]);
btnInsert = findViewById([Link]);
btnView = findViewById([Link]);

// Creates the database if it doesn't exist


SQLiteDatabase db = openOrCreateDatabase("SliteDb", Context.MODE_PRIVATE, null);
[Link]("CREATE TABLE IF NOT EXISTS records (id INTEGER PRIMARY KEY
AUTOINCREMENT, name VARCHAR, course VARCHAR, fee VARCHAR)");
[Link](new [Link]() {
@Override
public void onClick(View v) {
insertData(db);
}
});

[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), [Link]);
startActivity(i);
}
});
}

public void insertData(SQLiteDatabase db) {


try {
ContentValues values = new ContentValues();
[Link]("name", [Link]().toString());
[Link]("course", [Link]().toString());
[Link]("fee", [Link]().toString());

long result = [Link]("records", null, values);

if(result != -1) {
[Link](this, "Record Added Successfully", Toast.LENGTH_SHORT).show();
[Link]("");
[Link]("");
[Link]("");
[Link]();
} else {
[Link](this, "Failed to Add Record", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
[Link](this, "Error: " + [Link](), Toast.LENGTH_LONG).show();
}
}
}
4. activity_view.xml (List Screen)

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tap a student to Edit/Delete"
android:textAlignment="center"
android:padding="10dp"
android:textStyle="bold"/>

<ListView
android:id="@+id/lst1"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

5. [Link]

Java
package [Link]; // Change to your package name

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

public class ViewActivity extends AppCompatActivity {


ListView lst1;
ArrayList<String> titles = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
ArrayList<Student> studentList = new ArrayList<>();

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

lst1 = findViewById([Link].lst1);
SQLiteDatabase db = openOrCreateDatabase("SliteDb", Context.MODE_PRIVATE, null);

Cursor c = [Link]("select * from records", null);


int idIndex = [Link]("id");
int nameIndex = [Link]("name");
int courseIndex = [Link]("course");
int feeIndex = [Link]("fee");

[Link]();
[Link]();
arrayAdapter = new ArrayAdapter<>(this, [Link].simple_list_item_1, titles);
[Link](arrayAdapter);

if ([Link]()) {
do {
Student stu = new Student();
[Link] = [Link](idIndex);
[Link] = [Link](nameIndex);
[Link] = [Link](courseIndex);
[Link] = [Link](feeIndex);

[Link](stu);
[Link]([Link] + " | " + [Link] + " | " + [Link] + " | " + [Link]);
} while ([Link]());
[Link]();
}

[Link](new [Link]() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Student stu = [Link](position);
Intent i = new Intent(getApplicationContext(), [Link]);
[Link]("id", [Link]);
[Link]("name", [Link]);
[Link]("course", [Link]);
[Link]("fee", [Link]);
startActivity(i);
}
});
}
}

6. activity_edit.xml (Update/Delete Screen)

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit Registration"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginBottom="20dp"/>

<EditText
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:hint="ID" />

<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<EditText
android:id="@+id/course"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Course" />

<EditText
android:id="@+id/fee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Fee"
android:inputType="number"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">

<Button
android:id="@+id/btUpdate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Update" />

<Button
android:id="@+id/btDelete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Delete" />

<Button
android:id="@+id/btBack"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Back" />
</LinearLayout>

</LinearLayout>
7. [Link]

Java
package [Link]; // Change to your package name

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

public class EditActivity extends AppCompatActivity {


EditText edId, edName, edCourse, edFee;
Button btnUpdate, btnDelete, btnBack;

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

edId = findViewById([Link]);
edName = findViewById([Link]);
edCourse = findViewById([Link]);
edFee = findViewById([Link]);

btnUpdate = findViewById([Link]);
btnDelete = findViewById([Link]);
btnBack = findViewById([Link]);

// Fetch the data passed from ViewActivity


Intent i = getIntent();
[Link]([Link]("id"));
[Link]([Link]("name"));
[Link]([Link]("course"));
[Link]([Link]("fee"));
SQLiteDatabase db = openOrCreateDatabase("SliteDb", Context.MODE_PRIVATE, null);

[Link](new [Link]() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
[Link]("name", [Link]().toString());
[Link]("course", [Link]().toString());
[Link]("fee", [Link]().toString());

String studentId = [Link]().toString();

[Link]("records", values, "id=?", new String[]{studentId});


[Link]([Link], "Record
Updated",Toast.LENGTH_SHORT).show();
goBack();
}
});

[Link](new [Link]() {
@Override
public void onClick(View v) {
String studentId = [Link]().toString();
[Link]("records", "id=?", new String[]{studentId});
[Link]([Link], "Record Deleted",
Toast.LENGTH_SHORT).show();
goBack();
}
});

[Link](new [Link]() {
@Override
public void onClick(View v) {
goBack();
}
});
}

private void goBack() {


Intent i = new Intent(getApplicationContext(), [Link]);
startActivity(i);
finish();
}}
Program 10: Send and Receive SMS
Objective: Create an application to send an SMS message and use a BroadcastReceiver to listen
for incoming SMS messages.

Note for Students: To test this on an emulator, you can send an SMS to yourself! Your emulator's
phone number is usually the 4-digit number at the top of its window (e.g., 5554). Type 5554 into
the phone number field to see it send and receive instantly.

Instructions for Execution:


1.​ Create a new project named SMSApp (Empty Views Activity, Java, API 24).
2.​ Crucial Step: Navigate to app/src/main/[Link] and add the required
permissions for sending and receiving SMS messages.
3.​ Update activity_main.xml to create the input fields and a text view to display received
messages.
4.​ Update [Link] to handle the runtime permissions, send the text, and register
the receiver.
5.​ Run the app (Shift + F10). Accept the permission prompt, then test it by sending a
message to 5554.

Code Files:
1. [Link] (Add these above the <application> tag)

XML
<uses-permission android:name="[Link].SEND_SMS" />
<uses-permission android:name="[Link].RECEIVE_SMS" />
<uses-permission android:name="[Link].READ_PHONE_STATE" />

2. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter phone number (e.g. 5554)"
android:inputType="phone"
android:layout_marginBottom="16dp"/>

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter message"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/buttonSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_marginBottom="20dp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Received Messages:"
android:textStyle="bold"
android:textSize="18sp"
android:layout_marginBottom="10dp"/>

<TextView
android:id="@+id/textViewReceivedMessages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@android:color/black"
android:background="#EEEEEE"
android:padding="10dp"/>

</LinearLayout>

3. [Link]

Java
package [Link]; // Change to your package name

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [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 static final int SMS_PERMISSION_CODE = 101;


private EditText editTextPhoneNumber, editTextMessage;
private TextView textViewReceivedMessages;
private Button buttonSend;

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

editTextPhoneNumber = findViewById([Link]);
editTextMessage = findViewById([Link]);
textViewReceivedMessages = findViewById([Link]);
buttonSend = findViewById([Link]);

// Check and request permissions at runtime


if (!checkSMSPermission()) {
requestSMSPermission();
}

// Register the BroadcastReceiver to listen for incoming texts


IntentFilter intentFilter = new
IntentFilter("[Link].SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
[Link](new [Link]() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}

@Override
protected void onDestroy() {
[Link]();
// Always unregister receivers to prevent memory leaks
unregisterReceiver(smsReceiver);
}

private void sendMessage() {


String phoneNumber = [Link]().toString().trim();
String message = [Link]().toString();

if ([Link]() || [Link]()) {
[Link](this, "Please enter both phone number and message",
Toast.LENGTH_SHORT).show();
return;
}

if (checkSMSPermission()) {
try {
SmsManager smsManager = [Link]();
[Link](phoneNumber, null, message, null, null);
[Link](this, "Message sent", Toast.LENGTH_SHORT).show();
[Link](""); // Clear message box after sending
} catch (Exception e) {
[Link](this, "Failed to send message", Toast.LENGTH_SHORT).show();
[Link]();
}
} else {
[Link](this, "SMS Permission is required", Toast.LENGTH_SHORT).show();
}
}
private boolean checkSMSPermission() {
int sendPermission = [Link](this,
[Link].SEND_SMS);
int receivePermission = [Link](this,
[Link].RECEIVE_SMS);
return sendPermission == PackageManager.PERMISSION_GRANTED &&
receivePermission == PackageManager.PERMISSION_GRANTED;
}

private void requestSMSPermission() {


[Link](this, new String[]{
[Link].SEND_SMS,
[Link].RECEIVE_SMS,
[Link].READ_PHONE_STATE
}, SMS_PERMISSION_CODE);
}

// The BroadcastReceiver that catches incoming messages


private final BroadcastReceiver smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = [Link]();
if (bundle != null) {
Object[] pdus = (Object[]) [Link]("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = [Link]((byte[]) pdu);
String sender = [Link]();
String messageBody = [Link]();

[Link]("From: " + sender + "\n");


[Link]("Message: " + messageBody + "\n\n");
}
}
}
}
};
}
Program 11: Send an Email
Objective: Create an application that utilizes an Implicit Intent to pass data to an installed Email
client.

Note for Students: If you run this on a freshly created emulator, the device might not have an
email account logged in. Clicking "Send" will launch the Gmail app, but it may ask you to log in
first. This is normal and means your code successfully triggered the email application!

Instructions for Execution:


1.​ Create a new project named EmailApp (Empty Views Activity, Java, API 24).
2.​ Update activity_main.xml to create the input fields for the email address, subject, and
message body.
3.​ Update [Link] to capture the input and launch the ACTION_SENDTO intent.
4.​ Run the app (Shift + F10).

Code Files:
1. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center_horizontal">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Compose Email"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginBottom="20dp"
android:textAlignment="center"/>

<EditText
android:id="@+id/editTextTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To (e.g. test@[Link])"
android:inputType="textEmailAddress"
android:layout_marginBottom="16dp"/>

<EditText
android:id="@+id/editTextSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:layout_marginBottom="16dp"/>

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:hint="Message Body"
android:gravity="top|start"
android:inputType="textMultiLine"
android:layout_marginBottom="20dp"/>

<Button
android:id="@+id/buttonSend"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Send Email" />

</LinearLayout>

2. [Link]

Java
package [Link]; // Change to your package name

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {

EditText editTextTo, editTextSubject, editTextMessage;


Button buttonSend;

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

editTextTo = findViewById([Link]);
editTextSubject = findViewById([Link]);
editTextMessage = findViewById([Link]);
buttonSend = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
sendEmail();
}
});
}

private void sendEmail() {


String to = [Link]().toString().trim();
String subject = [Link]().toString().trim();
String message = [Link]().toString().trim();

if ([Link]()) {
[Link](this, "Please enter a recipient email", Toast.LENGTH_SHORT).show();
return;
}

// ACTION_SENDTO with a "[Link] URI ensures that only email apps will respond to
this intent
Intent intent = new Intent(Intent.ACTION_SENDTO);
[Link]([Link]("[Link]

[Link](Intent.EXTRA_EMAIL, new String[]{to});


[Link](Intent.EXTRA_SUBJECT, subject);
[Link](Intent.EXTRA_TEXT, message);

// Verify that the user has an email app installed before trying to launch it
if ([Link](getPackageManager()) != null) {
startActivity([Link](intent, "Choose an email client"));
} else {
[Link](this, "No email client installed", Toast.LENGTH_SHORT).show();
}
}
}
Program 12: Display a Google Map
Objective: Display a Google Map centered on a specific given location using the Google Maps
API.

Note for Students: A Google Map will only load if you have a valid API Key. Without it, the app
will compile, but the screen will show a blank grid with a Google logo. Your professor will
provide instructions if you are required to generate a real API key for this lab.

Instructions for Execution:

1.​ Create a new project named MapsApp (Empty Views Activity, Java, API 24).
2.​ Crucial Setup Step: Open app/[Link] (Module level). Inside the dependencies { ...
} block, add this line: implementation
'[Link]:play-services-maps:18.2.0' Click "Sync Now" in the top right
corner.
3.​ Update [Link] to include internet permissions and the API Key metadata
tag.
4.​ Update activity_main.xml with the Map Fragment.
5.​ Update [Link] to initialize the map and set the coordinates.
6.​ Run the app (Shift + F10).

Code Files:

1. [Link] (Add before and inside the <application> tag)

XML
<uses-permission android:name="[Link]" />
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION" />
<uses-permission android:name="[Link].ACCESS_COARSE_LOCATION" />

<meta-data
android:name="[Link].API_KEY"
android:value="YOUR_API_KEY_HERE" />

2. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/map"
android:name="[Link]"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

3. [Link]

Java
package [Link]; // Change to your package name

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 implements OnMapReadyCallback {

private GoogleMap mMap;

// Coordinates for Bengaluru (Change as needed)


private double latitude = 12.9716;
private double longitude = 77.5946;

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

// Link the fragment from XML and initialize the map


SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById([Link]);

if (mapFragment != null) {
[Link](this);
} else {
[Link](this, "Map Fragment Not Found", Toast.LENGTH_SHORT).show();
}
}

// This method triggers automatically once the map is fully loaded


@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;

// Create a location variable using our coordinates


LatLng targetLocation = new LatLng(latitude, longitude);

// Place a red pin on the map


[Link](new MarkerOptions().position(targetLocation).title("Marker in
Bengaluru"));

// Move the camera to the pin and zoom in (15 is a good city-level zoom)
[Link]([Link](targetLocation, 15));
}
}
Program 13: Simple Login Module with Toast/TextView
Updates
Objective: Create an application to validate a username and password. On success, update a
TextView; on failure, trigger a Toast message.

Instructions for Execution:

1.​ Create a new project named SimpleLoginApp (Empty Views Activity, Java, API 24).
2.​ Update activity_main.xml to create the input fields, login button, and status text view.
3.​ Update [Link] to validate the credentials (we will use isbr as the username
and password, as defined in the syllabus).
4.​ Run the app (Shift + F10).

Code Files:

1. activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp"
android:gravity="center_horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Portal Login"
android:textSize="26sp"
android:textStyle="bold"
android:layout_marginBottom="40dp" />

<EditText
android:id="@+id/etUsername"
android:layout_width="match_parent"
android:layout_height="60dp"
android:hint="Username"
android:inputType="text"
android:layout_marginBottom="20dp" />
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="60dp"
android:hint="Password"
android:inputType="textPassword"
android:layout_marginBottom="30dp" />

<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Login"
android:textSize="18sp"
android:layout_marginBottom="20dp" />

<TextView
android:id="@+id/tvMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="20sp"
android:textColor="#4CAF50"
android:textStyle="bold" />

</LinearLayout>

2. [Link]

Java
package [Link]; // Change to your package name

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {

EditText etUsername, etPassword;


Button btnLogin;
TextView tvMessage;

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

etUsername = findViewById([Link]);
etPassword = findViewById([Link]);
btnLogin = findViewById([Link]);
tvMessage = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View view) {
String user = [Link]().toString().trim();
String pass = [Link]().toString().trim();

// Validation logic
if ([Link]()) {
[Link]("Enter Username");
} else if ([Link]()) {
[Link]("Enter Password");
} else if ([Link]("isbr") && [Link]("isbr")) {
// Update TextView on Success
[Link]("Login Successful!");
} else {
// Trigger Toast on Failure
[Link](""); // Clear previous success message if any
[Link]([Link], "Login Fail", Toast.LENGTH_LONG).show();
}
}
});
}
}
Program 14: Learn to Deploy Android Applications
Objective: Understand the steps required to package a finished Android project into an
executable file (APK) that can be installed on physical phones or uploaded to the Google Play
Store.

Instructions for Generating a Signed APK:

When your application is complete and bug-free, you must compile it into an APK (Android
Package Kit) to distribute it.

Step 1: Initiating the Build and Signature Process

The first action is to access the dedicated tool within the IDE that manages the signing and
packaging of the application.

1.​ Access the Top Menu Bar: Navigate to the very top of the Android Studio window
where the primary application menus are located (e.g., File, Edit, View, Build).
2.​ Select the Build Menu: Click on the Build menu item. This dropdown contains all the
compilation and assembly options.
3.​ Launch the Signature Wizard: From the dropdown list, select Generate Signed
Bundle / APK.... This command initiates a multi-step wizard to guide you through the
signing and compilation requirements.

Step 2: Choosing the Appropriate Output Format

The wizard will prompt you to decide how the application should be packaged. While the
Android App Bundle (AAB) is the modern, recommended format for submission to Google Play,
the APK is the required format for direct, non-Store distribution.

1.​ Selection Window: A new dialog box will appear, presenting the two primary choices:
Android App Bundle and APK.
2.​ Select APK: Choose the APK radio button. This format creates a single, self-contained
installation file (.apk) that can be sideloaded onto any compatible Android device.
3.​ Proceed: Click Next to move to the security and signing configuration.

Step 3: Creating and Configuring the Keystore (Digital Signature)

The Keystore is the single most critical security element. It is a highly secure, encrypted file that
contains the private key used to digitally sign your application. This signature is what proves
your identity as the original developer. It is vital to back up and secure this file; losing it
means you can never update your app.
1.​ Locate the Keystore Field: In the "Key store path" section, if you do not have a
previously created Keystore, click the Create new... button.
2.​ Choose a Secure Location: A file explorer window will open. Select a safe, backed-up
folder on your computer to save this new Keystore file (e.g., a dedicated signing-keys
directory, not within your project folder).
3.​ Set the Keystore Password:
○​ Create a strong, unique master password for the Keystore file itself. You will
need this password every time you generate a signed release build.
○​ Keystore Path: The full file path will automatically populate upon selection.
4.​ Define the Key Alias and Password:
○​ Key Alias: Enter a unique identifier (an Alias) for the specific private key being
generated (e.g., my_app_production_key). This allows one Keystore file to hold
multiple keys.
○​ Key Password: Create a separate, strong password specifically for this individual
key alias.
5.​ Enter Certificate Information: To identify the creator, fill in at least one field under the
"Certificate" section. This information is embedded in the app's signature and is typically
used for identification. Common entries include:
○​ First and Last Name
○​ Organizational Unit (e.g., "Development")
○​ Organization (e.g., "Acme Corp")
○​ City or Locality
○​ State or Province
○​ Country Code (e.g., IN, US)
6.​ Finalize Key Creation: Click OK to generate the Keystore and key pair, then click Next
in the main wizard window to proceed.

Step 4: Specifying the Release Build Configuration

This step configures the final compilation settings for the APK file.

1.​ Define the Output Path: Verify the destination folder where the final signed APK will
be placed. You can change this if necessary.
2.​ Select the Build Variant:
○​ Choose the release variant from the dropdown menu. The 'debug' variant includes
additional developer tools, logging, and less optimization, making it unsuitable
for public distribution. The release variant is optimized for performance and size.
3.​ Configure Signature Versions (Crucial for Compatibility): Check both signature
scheme boxes to ensure maximum compatibility across all Android devices:
○​ V1 (Jar Signature): The older, traditional signature scheme. It ensures
compatibility with older versions of Android.
○​ V2 (Full APK Signature): A faster, more secure signature scheme introduced in
Android 7.0 (Nougat). It is highly recommended to check both V1 and V2.
4.​ Initiate Generation: Click Finish. Android Studio will now perform the final
compilation, optimization, signing, and packaging of your application. This process may
take several minutes depending on the size and complexity of your project.

Step 5: Locating and Distributing Your Application File

Once the build process is complete, Android Studio provides a direct link to the resulting file.

1.​ Wait for Build Completion: Monitor the bottom right corner of the Android Studio
window. Wait for the green "Build Successful" notification to appear.
2.​ Locate the File: Click the locate hyperlink embedded within the success notification.
This immediately opens the system file explorer directly to the directory containing the
newly generated APK.
3.​ Identify the Final File: The file will typically be named in the format:
app-[module_name]-[Link].
4.​ Distribution: This signed [Link] file is now ready for distribution. You can:
○​ Transfer it directly via a USB cable.
○​ Send it as an attachment via email.
○​ Upload it to a cloud storage service or website for users to download and install
(sideload) directly onto their physical Android devices.

You might also like