0% found this document useful (0 votes)
21 views78 pages

Androidlab Manual Upto16

The document outlines a series of experiments for creating Android applications using Android Studio, focusing on different functionalities such as displaying 'Hello World', showing toast messages, calculating factorials, and using checkboxes. Each experiment includes step-by-step instructions, required tools, and code snippets in both Java and Kotlin. The document serves as a practical guide for beginners to learn Android programming through hands-on projects.
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)
21 views78 pages

Androidlab Manual Upto16

The document outlines a series of experiments for creating Android applications using Android Studio, focusing on different functionalities such as displaying 'Hello World', showing toast messages, calculating factorials, and using checkboxes. Each experiment includes step-by-step instructions, required tools, and code snippets in both Java and Kotlin. The document serves as a practical guide for beginners to learn Android programming through hands-on projects.
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
You are on page 1/ 78

Android Programming Lab Manual

EXPERIMENT NO:1

AIM: Create an Android Application To display "Hello World".

Tools Required

• Android Studio

• Android SDK

• Java or Kotlin (default programming languages for Android)

Steps

1. Setting up Android Studio

• Download and install Android Studio.

• Open Android Studio and select "Start a new Android Studio project".

2. Creating a New Project

• Choose "Empty Activity" as the template for the project.

• Click Next.
Configure your project:

• Name: HelloWorldApp

• Package name: com.example.helloworldapp

• Save location: Select a location to save the project on your computer.

• Language: Choose either Kotlin or Java.

• Minimum API Level: Select API 21: Android 5.0 (Lollipop) or later.

• Click Finish.

3. Editing the Main Layout

• Once the project is created, go to the res/layout/activity_main.xml file.

• You'll find a basic layout file containing a TextView element.

• Modify it to display "Hello World!"

CODE:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"
android:textSize="24sp"

android:textColor="@android:color/black" />

</LinearLayout>

4. Editing the Main Activity

• Navigate to MainActivity.kt file located in java/com.example.helloworldapp/.

• This file already contains the code for setting up the main activity. Since our goal is simple, no
modifications are required to this file.

CODE2:

package com.example.helloworldapp

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

}
5. Running the Application

• Plug in your Android device or use the Android Emulator.

• Click on the Run button in Android Studio or press Shift + F10.

• Choose your device from the list, and the application will be installed and launched.

• You should see "Hello World!" displayed on the screen.


EXPERIMENT NO:2

AIM: Create an Android Application To display a Toast Message

Tools and Technologies

• Android Studio

• Kotlin/Java (we'll use Kotlin for this example)

• Android SDK

Step 1: Setting Up Your Project

1. Open Android Studio:

o Launch Android Studio and select New Project.

2. Choose Project Template:

o Select Empty Activity and click Next.

3. Configure Your Project:

o Name: ToastMessageApp

o Package name: com.example.toastmessageapp

o Save Location: Choose your desired location.

o Language: Kotlin

o Minimum API Level: API 21 (Android 5.0 Lollipop) or higher.

4. Click Finish:

o Android Studio will take a few moments to set up your project.

Step 2: Designing the User Interface (UI)

1. Open activity_main.xml:

o Navigate to the res/layout/activity_main.xml file in the project structure.

2. Modify the Layout:

o Add a Button in the XML file to trigger the toast message.


o Replace the default content with the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent">

<Button

android:id="@+id/button_toast"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Toast"

android:layout_centerInParent="true" />

</RelativeLayout>

Step 3: Writing the Code

1. Open MainActivity.kt:

o Navigate to the MainActivity.kt file in the java/com.example.toastmessageapp


directory.

2. Modify the MainActivity Code:

o Add the logic to display a toast when the button is clicked.

o Replace the existing code with the following:

CODE2:

package com.example.toastmessageapp

import android.os.Bundle

import android.widget.Button

import android.widget.Toast

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

// Get the button reference

val buttonToast: Button = findViewById(R.id.button_toast)

// Set a click listener to show the toast message

buttonToast.setOnClickListener {

Toast.makeText(this, " This a simple toast message", Toast.LENGTH_SHORT).show()

Step 4: Running the Application

1. Build and Run:

o Click the green "Run" button (or Shift + F10) in Android Studio.

o Choose a connected device or an emulator to run the app.

2. Test the Application:

o Once the app is installed and running on the device/emulator, click the Show Toast
button.

o A toast message saying "This a simple toast message" should appear on the screen.
EXPERIMENT NO:3

AIM: Create an Android app to accept a number in textfield and display the factorial of it in a Tou
message on clicking a button.

1. Create a New Android Project:

• Open Android Studio.

• Start a new Android Studio project and choose the Empty Activity template.

• Name the project (e.g., FactorialApp).

2. Update activity_main.xml:

Design your UI to have:

• An EditText for the user to input a number.

• A Button to trigger the factorial calculation.

• Here's the XML for the layout (activity_main.xml):

Xml:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
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">

<EditText

android:id="@+id/inputNumber"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:hint="Enter a number"

android:inputType="number"

android:layout_marginTop="32dp"

android:layout_marginHorizontal="16dp"

app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

<Button

android:id="@+id/calculateButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Calculate Factorial"

android:layout_marginTop="16dp"

app:layout_constraintTop_toBottomOf="@id/inputNumber"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. MainActivity Code:

Java:

package com.example.factorialapp;

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText inputNumber;

Button calculateButton;
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

inputNumber = findViewById(R.id.inputNumber);

calculateButton = findViewById(R.id.calculateButton);

calculateButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String input = inputNumber.getText().toString();

if (!TextUtils.isEmpty(input)) {

int number = Integer.parseInt(input);

long factorialResult = calculateFactorial(number);

Toast.makeText(MainActivity.this, "Factorial: " + factorialResult,


Toast.LENGTH_LONG).show();

} else {

Toast.makeText(MainActivity.this, "Please enter a number",


Toast.LENGTH_SHORT).show();

});

private long calculateFactorial(int num) {

long factorial = 1;

for (int i = 2; i <= num; i++) {

factorial *= i;

}
return factorial;

Kotlin (MainActivity.kt):

package com.example.factorialapp

import android.os.Bundle

import android.text.TextUtils

import android.widget.Button

import android.widget.EditText

import android.widget.Toast

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

lateinit var inputNumber: EditText

lateinit var calculateButton: Button

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

inputNumber = findViewById(R.id.inputNumber)

calculateButton = findViewById(R.id.calculateButton)

calculateButton.setOnClickListener {

val input = inputNumber.text.toString()

if (!TextUtils.isEmpty(input)) {

val number = input.toInt()

val factorialResult = calculateFactorial(number)

Toast.makeText(this, "Factorial: $factorialResult", Toast.LENGTH_LONG).show()

} else {

Toast.makeText(this, "Please enter a number", Toast.LENGTH_SHORT).show()

private fun calculateFactorial(num: Int): Long {


var factorial: Long = 1

for (i in 2..num) {

factorial *= i

return factorial

4. Explanation:

• EditText (inputNumber) is used to accept the number input.

• Button (calculateButton) is used to trigger the factorial calculation when clicked.

• Toast is used to display the result or any error messages.

• The factorial calculation is done in the calculateFactorial() function, which multiplies the
numbers from 1 up to the input number.

5. Run the App:

• Build and run the app on an Android device or emulator.

• Enter a number, click the button, and the factorial result will be displayed in a Toast message.
EXPERIMENT NO:4

AIM: Create an Android app to illustrate the use of CheckBoxwidget.

Tools & Technologies Required:

• Android Studio

• Java/Kotlin programming language

• Android SDK

App Components:

• Activity: The main UI where checkboxes are displayed.

• CheckBox Widget: Allows users to select or deselect options.

• Button: Used to submit the selected choices.

• Toast: Displays the selected choices.

Step-by-Step Procedure:

1. Create a New Android Project:

• Open Android Studio.

• Select File > New > New Project.

• Choose Empty Activity and name the project (e.g., CheckBoxApp).

2. Update activity_main.xml:

In the layout XML file, we will design the UI to contain multiple CheckBox widgets and a Button.

Xml:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
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">

<TextView

android:id="@+id/tvTitle"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Choose Your Hobbies"

android:textSize="20sp"

android:layout_marginTop="30dp"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"/>

<CheckBox

android:id="@+id/checkBoxReading"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Reading"

app:layout_constraintTop_toBottomOf="@id/tvTitle"

app:layout_constraintStart_toStartOf="parent"

android:layout_marginTop="20dp"

android:layout_marginStart="20dp"/>

<CheckBox

android:id="@+id/checkBoxTraveling"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Traveling"

app:layout_constraintTop_toBottomOf="@id/checkBoxReading"

app:layout_constraintStart_toStartOf="parent"

android:layout_marginTop="20dp"

android:layout_marginStart="20dp"/>

<CheckBox

android:id="@+id/checkBoxGaming"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Gaming"

app:layout_constraintTop_toBottomOf="@id/checkBoxTraveling"

app:layout_constraintStart_toStartOf="parent"

android:layout_marginTop="20dp"

android:layout_marginStart="20dp"/>

<Button

android:id="@+id/btnSubmit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

app:layout_constraintTop_toBottomOf="@id/checkBoxGaming"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

android:layout_marginTop="40dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

3. MainActivity Code:

Next, handle the logic for checking the selected checkboxes and displaying the result using a Toast
message.

MainActivity.java (Java):

package com.example.checkboxapp;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.CheckBox;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

CheckBox checkBoxReading, checkBoxTraveling, checkBoxGaming;

Button btnSubmit;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

checkBoxReading = findViewById(R.id.checkBoxReading);

checkBoxTraveling = findViewById(R.id.checkBoxTraveling);

checkBoxGaming = findViewById(R.id.checkBoxGaming);

btnSubmit = findViewById(R.id.btnSubmit);

btnSubmit.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

StringBuilder result = new StringBuilder();

result.append("Selected Hobbies: \n");

if (checkBoxReading.isChecked()) {

result.append("Reading\n");

if (checkBoxTraveling.isChecked()) {

result.append("Traveling\n");

if (checkBoxGaming.isChecked()) {

result.append("Gaming\n");

}
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();

});

MainActivity.kt (Kotlin):

package com.example.checkboxapp

import android.os.Bundle

import android.widget.Button

import android.widget.CheckBox

import android.widget.Toast

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

lateinit var checkBoxReading: CheckBox

lateinit var checkBoxTraveling: CheckBox

lateinit var checkBoxGaming: CheckBox

lateinit var btnSubmit: Button

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

checkBoxReading = findViewById(R.id.checkBoxReading)

checkBoxTraveling = findViewById(R.id.checkBoxTraveling)

checkBoxGaming = findViewById(R.id.checkBoxGaming)

btnSubmit = findViewById(R.id.btnSubmit)
btnSubmit.setOnClickListener {

val result = StringBuilder()

result.append("Selected Hobbies: \n")

if (checkBoxReading.isChecked) result.append("Reading\n")

if (checkBoxTraveling.isChecked) result.append("Traveling\n")

if (checkBoxGaming.isChecked) result.append("Gaming\n")

Toast.makeText(this, result.toString(), Toast.LENGTH_LONG).show()

4. Explanation of Code:

• CheckBox Widgets: These are UI elements that let users select multiple options.

• Button: Triggers an event (onClick) to capture the user's selected choices.

• Toast: Displays the selected items in a pop-up message.

• We first reference each UI component using findViewById, then use setOnClickListener to


perform the action when the user clicks the submit button.

6. Run the Application:

• Connect your Android device or use the emulator.

• Build and run the app.

• The user will see the checkboxes and can select options. After clicking "Submit", the selected
hobbies will be shown in a Toast message.
EXPERIMENT NO:5

AIM: Create an Android app to illustrate the use of Spinner (ComboBox)widget.

Step 1: Create a New Android Project

1. Open Android Studio and create a new project.

o Select New Project > Empty Activity.

o Set the Project Name as SpinnerApp.

o Set Package Name, Save Location, Language (Java or Kotlin), and Minimum API
Level.

o Click Finish to create the project.

Step 2: Modify the Layout XML to Add a Spinner Widget

1. Open res/layout/activity_main.xml.

2. Add the Spinner widget to the layout file as shown below:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
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">

<Spinner

android:id="@+id/spinner"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:spinnerMode="dropdown"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

android:layout_marginTop="50dp" />

<TextView
android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="30dp"

app:layout_constraintTop_toBottomOf="@+id/spinner"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

android:text="Selected Item"

android:textSize="18sp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Define the Data for the Spinner in strings.xml

1. Open res/values/strings.xml.

2. Add a string array for the Spinner items:

<resources>

<string name="app_name">SpinnerApp</string>

<string-array name="items_array">

<item>Item 1</item>

<item>Item 2</item>

<item>Item 3</item>

<item>Item 4</item>

</string-array>

</resources>

Step 4: Write Code in MainActivity.java or MainActivity.kt

For Java:

1. Open MainActivity.java.

2. Add the following code to populate the Spinner and handle selection events:

package com.example.spinnerapp;

import android.os.Bundle;

import android.view.View;
import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.Spinner;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Reference to Spinner and TextView

Spinner spinner = findViewById(R.id.spinner);

TextView textView = findViewById(R.id.textView);

// Create ArrayAdapter using string-array

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,

R.array.items_array, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// Set the adapter to the Spinner

spinner.setAdapter(adapter);

// Set the item selection listener

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override

public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position,


long id) {

// Get selected item


String selectedItem = parentView.getItemAtPosition(position).toString();

textView.setText("Selected: " + selectedItem);

@Override

public void onNothingSelected(AdapterView<?> parentView) {

// Handle when no item is selected

textView.setText("No selection made");

});

For Kotlin:

1. Open MainActivity.kt.

2. Add the following code to populate the Spinner and handle selection events:

package com.example.spinnerapp

import android.os.Bundle

import android.view.View

import android.widget.AdapterView

import android.widget.ArrayAdapter

import android.widget.Spinner

import android.widget.TextView

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)
// Reference to Spinner and TextView

val spinner: Spinner = findViewById(R.id.spinner)

val textView: TextView = findViewById(R.id.textView)

// Create ArrayAdapter using string-array

ArrayAdapter.createFromResource(

this,

R.array.items_array,

android.R.layout.simple_spinner_item

).also { adapter ->

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

spinner.adapter = adapter

// Set the item selection listener

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {

// Get selected item

val selectedItem = parent.getItemAtPosition(position).toString()

textView.text = "Selected: $selectedItem"

override fun onNothingSelected(parent: AdapterView<*>) {

textView.text = "No selection made"

}
Step 5: Build and Run the Application

1. Build the Project: Go to Build > Make Project to ensure the code compiles without errors.

2. Run the Application: Connect an Android device or launch an emulator, and click the Run
button to deploy the app.

Output:
EXPERIMENT NO:6

AIM: Create an Android app to illustrate the use of Datepickerwidget and Timepickerwidget.

Step 1: Create a New Android Project

1. Open Android Studio and create a new project:

o Select New Project > Empty Activity.

o Set the Project Name as DateTimePickerApp.

o Choose Java or Kotlin as the programming language.

o Set the Minimum API Level (e.g., API 21: Android 5.0 Lollipop).

o Click Finish.

Step 2: Modify the Layout XML to Add DatePicker and TimePicker Widgets

1. Open res/layout/activity_main.xml.

2. Update the XML code to include DatePicker, TimePicker, and TextView widgets:

xml

Copy code

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
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">

<DatePicker

android:id="@+id/datePicker"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

android:layout_marginTop="50dp" />
<TimePicker

android:id="@+id/timePicker"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintTop_toBottomOf="@+id/datePicker"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

android:layout_marginTop="50dp" />

<TextView

android:id="@+id/resultTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="30dp"

app:layout_constraintTop_toBottomOf="@+id/timePicker"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

android:text="Selected Date and Time"

android:textSize="18sp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Implement DatePicker and TimePicker in MainActivity

1. Open MainActivity.java or MainActivity.kt.

For Java:

1. Open MainActivity.java.

2. Implement the following code to handle DatePicker and TimePicker events:

java

Copy code

package com.example.datetimepickerapp;
import android.app.DatePickerDialog;

import android.app.TimePickerDialog;

import android.os.Bundle;

import android.view.View;

import android.widget.DatePicker;

import android.widget.TextView;

import android.widget.TimePicker;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private TextView resultTextView;

private int year, month, day, hour, minute;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

resultTextView = findViewById(R.id.resultTextView);

DatePicker datePicker = findViewById(R.id.datePicker);

TimePicker timePicker = findViewById(R.id.timePicker);

// Initialize calendar instance

Calendar calendar = Calendar.getInstance();

year = calendar.get(Calendar.YEAR);

month = calendar.get(Calendar.MONTH);

day = calendar.get(Calendar.DAY_OF_MONTH);

hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);

// Set the TimePicker to 24-hour format

timePicker.setIs24HourView(true);

// DatePicker listener

datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {

@Override

public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

MainActivity.this.year = year;

MainActivity.this.month = monthOfYear;

MainActivity.this.day = dayOfMonth;

updateResult();

});

// TimePicker listener

timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

@Override

public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

MainActivity.this.hour = hourOfDay;

MainActivity.this.minute = minute;

updateResult();

});

private void updateResult() {

String date = String.format("%d/%d/%d", month + 1, day, year);

String time = String.format("%02d:%02d", hour, minute);

resultTextView.setText(String.format("Selected Date: %s\nSelected Time: %s", date, time));


}

For Kotlin:

1. Open MainActivity.kt.

2. Implement the following code to handle DatePicker and TimePicker events:

kotlin

Copy code

package com.example.datetimepickerapp

import android.os.Bundle

import android.widget.DatePicker

import android.widget.TextView

import android.widget.TimePicker

import androidx.appcompat.app.AppCompatActivity

import java.util.*

class MainActivity : AppCompatActivity() {

private lateinit var resultTextView: TextView

private var year: Int = 0

private var month: Int = 0

private var day: Int = 0

private var hour: Int = 0

private var minute: Int = 0

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

resultTextView = findViewById(R.id.resultTextView)

val datePicker: DatePicker = findViewById(R.id.datePicker)


val timePicker: TimePicker = findViewById(R.id.timePicker)

// Initialize calendar instance

val calendar = Calendar.getInstance()

year = calendar.get(Calendar.YEAR)

month = calendar.get(Calendar.MONTH)

day = calendar.get(Calendar.DAY_OF_MONTH)

hour = calendar.get(Calendar.HOUR_OF_DAY)

minute = calendar.get(Calendar.MINUTE)

// Set the TimePicker to 24-hour format

timePicker.is24HourView = true

// DatePicker listener

datePicker.init(year, month, day) { _, y, m, d ->

year = y

month = m

day = d

updateResult()

// TimePicker listener

timePicker.setOnTimeChangedListener { _, h, m ->

hour = h

minute = m

updateResult()

private fun updateResult() {

val date = String.format("%d/%d/%d", month + 1, day, year)


val time = String.format("%02d:%02d", hour, minute)

resultTextView.text = "Selected Date: $date\nSelected Time: $time"

Step 4: Build and Run the Application

1. Build the Project: Go to Build > Make Project to ensure there are no compilation errors.

2. Run the Application: Connect an Android device or use an emulator, and click the Run
button to deploy the app.

Output:
EXPERIMENT NO:7

AIM: Create an Android app that uses multiple UI controls like EditText, CheckBox, Spinner and
Buttons

Step 1: Create a New Project in Android Studio

1. Open Android Studio.

2. Click on File > New > New Project.

3. Select Empty Activity and click Next.

4. Name your project (e.g., "MultipleUIControlsApp").

5. Choose a minimum API level (e.g., API 21 or higher).

6. Click Finish.

Step 2: Design the Layout (XML)

• File Path: res/layout/activity_main.xml

In this step, you will create a layout that includes an EditText, CheckBox, Spinner, and Button.

CODE1:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

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">

<!-- EditText for user input -->

<EditText

android:id="@+id/editTextName"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:layout_margin="16dp"

app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent" />

<!-- CheckBox for user preference -->

<CheckBox

android:id="@+id/checkBoxSubscribe"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Subscribe to newsletter"

android:layout_marginTop="16dp"

app:layout_constraintTop_toBottomOf="@+id/editTextName"

app:layout_constraintLeft_toLeftOf="parent" />

<!-- Spinner for selecting an option -->

<Spinner

android:id="@+id/spinnerOptions"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="16dp"

app:layout_constraintTop_toBottomOf="@+id/checkBoxSubscribe"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent" />

<!-- Button to trigger action -->

<Button

android:id="@+id/buttonSubmit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:layout_marginTop="16dp"

app:layout_constraintTop_toBottomOf="@+id/spinnerOptions"
app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent" />

<!-- TextView to display output -->

<TextView

android:id="@+id/textViewResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="16dp"

app:layout_constraintTop_toBottomOf="@+id/buttonSubmit"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Initialize UI Components in Code

• File Path: java/com.example.yourappname/MainActivity.java

Now, initialize these UI controls and handle the user input in Java/Kotlin.

MainActivity (Java):

package com.example.multipleuicontrolsapp;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.Spinner;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


EditText editTextName;

CheckBox checkBoxSubscribe;

Spinner spinnerOptions;

Button buttonSubmit;

TextView textViewResult;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize UI components

editTextName = findViewById(R.id.editTextName);

checkBoxSubscribe = findViewById(R.id.checkBoxSubscribe);

spinnerOptions = findViewById(R.id.spinnerOptions);

buttonSubmit = findViewById(R.id.buttonSubmit);

textViewResult = findViewById(R.id.textViewResult);

// Handle button click

buttonSubmit.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String name = editTextName.getText().toString();

String subscribe = checkBoxSubscribe.isChecked() ? "Subscribed" : "Not Subscribed";

String option = spinnerOptions.getSelectedItem().toString();

String result = "Name: " + name + "\nSubscription: " + subscribe + "\nOption: " + option;

textViewResult.setText(result);

});

}
}

Step 4: Populate Spinner Options

To populate the Spinner with options, add an array to the strings.xml file.

• File Path: res/values/strings.xml

<resources>

<string name="app_name">Multiple UI Controls App</string>

<!-- Spinner options -->

<string-array name="spinner_options">

<item>Option 1</item>

<item>Option 2</item>

<item>Option 3</item>

</string-array>

</resources>

Now, go back to the MainActivity.java file and set up an adapter to bind this array to the Spinner:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,

R.array.spinner_options, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinnerOptions.setAdapter(adapter);

Step 5: Run the App


1. Click on the Run button or press Shift + F10 in Android Studio to build and run your app.

2. Choose a device or emulator to launch the app.

3. Input data in the EditText, select/deselect the CheckBox, choose an option from the Spinner,
and click the Button to see the results.
EXPERIMENT NO:8

AIM: Create an Android app to shift from one activity to another activity using a button.

1. Create a New Android Project:

• Open Android Studio.

• Select File -> New -> New Project.

• Enter project details such as project name, package name, etc.

• Select Empty Activity and click Finish.

2. Creating a Second Activity:

You need two activities: MainActivity and SecondActivity.

• Go to File -> New -> Activity -> Empty Activity.

• Name the second activity as SecondActivity and click Finish.

3. Design Layout for MainActivity:

• Open res/layout/activity_main.xml.

• Add a Button widget to the layout.

CODE 1:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

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">

<Button

android:id="@+id/buttonShift"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Go to Second Activity"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. Design Layout for SecondActivity:

• Open res/layout/activity_second.xml.

• Add a simple TextView to the layout:

CODE2:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

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=".SecondActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Welcome to the Second Activity"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

5. Code for MainActivity:

• Open MainActivity.java or MainActivity.kt.

• Add code to handle the button click and start SecondActivity.

package com.example.myapp;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button buttonShift = findViewById(R.id.buttonShift);

buttonShift.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

startActivity(intent);

});

6. Code for SecondActivity:

• SecondActivity will display a simple message. No special functionality is required.

package com.example.myapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
public class SecondActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

7. Update the AndroidManifest.xml:

• Declare the SecondActivity in the AndroidManifest.xml file. This ensures Android knows
about the new activity.

<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.MyApp">

<activity android:name=".SecondActivity"></activity>

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

8. Run the Application:

• Connect an Android device or use the Android Emulator.

• Run the application by clicking Run -> Run 'app'.

• The app should open on the device, showing a button.


• On pressing the button, it should navigate to SecondActivity displaying the "Welcome"
message.

Expected Output:

• The app initially displays the MainActivity screen with a button.

• On clicking the button, the app transitions to SecondActivity and displays a simple text
message.
EXPERIMENT 9:

AIM: Create an Android Application Using Image Effects

Step 1: Set Up the Android Project

1. Open Android Studio and create a new project.

2. Choose "Empty Activity" and click Next.

3. Name your application (e.g., ImageEffectsApp).

4. Set the language to Java or Kotlin.

5. Click Finish to create the project.

Step 2: Design the User Interface

1. Open activity_main.xml and design the layout:

o Add an ImageView to display the selected image.

o Add Button elements for selecting an image and applying effects (e.g., Grayscale,
Sepia, Blur).

o Add a ScrollView or RecyclerView if you want to display a list of effects.

<!-- activity_main.xml -->

<RelativeLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent">

<ImageView

android:id="@+id/imageView"

android:layout_width="match_parent"

android:layout_height="400dp"

android:scaleType="centerCrop"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"/>

<Button

android:id="@+id/btnSelectImage"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Select Image"

android:layout_below="@id/imageView"

android:layout_centerHorizontal="true"/>

<Button

android:id="@+id/btnApplyGrayscale"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Grayscale"

android:layout_below="@id/btnSelectImage"

android:layout_marginTop="8dp"

android:layout_centerHorizontal="true"/>

<!-- Add more buttons for different effects -->

</RelativeLayout>

Step 3: Implement Image Selection

1. In MainActivity.java or MainActivity.kt, implement code to select an image from the gallery


using an Intent.

// MainActivity.java

public class MainActivity extends AppCompatActivity {

private static final int PICK_IMAGE = 1;

private ImageView imageView;

private Bitmap originalBitmap, processedBitmap;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);

Button btnSelectImage = findViewById(R.id.btnSelectImage);

Button btnApplyGrayscale = findViewById(R.id.btnApplyGrayscale);

btnSelectImage.setOnClickListener(view -> openGallery());

btnApplyGrayscale.setOnClickListener(view -> {

if (originalBitmap != null) {

processedBitmap = applyGrayscaleEffect(originalBitmap);

imageView.setImageBitmap(processedBitmap);

});

private void openGallery() {

Intent intent = new Intent(Intent.ACTION_PICK,


MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(intent, PICK_IMAGE);

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {

Uri imageUri = data.getData();

try {

originalBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),
imageUri);

imageView.setImageBitmap(originalBitmap);

} catch (IOException e) {

e.printStackTrace();
}

Step 4: Implement Image Effects

1. Add methods to apply different effects like Grayscale, Sepia, Blur, etc.

// Grayscale Effect

private Bitmap applyGrayscaleEffect(Bitmap src) {

int width = src.getWidth();

int height = src.getHeight();

Bitmap grayscaleBitmap = Bitmap.createBitmap(width, height, src.getConfig());

for (int x = 0; x < width; x++) {

for (int y = 0; y < height; y++) {

int pixel = src.getPixel(x, y);

int red = Color.red(pixel);

int green = Color.green(pixel);

int blue = Color.blue(pixel);

int gray = (red + green + blue) / 3;

grayscaleBitmap.setPixel(x, y, Color.rgb(gray, gray, gray));

return grayscaleBitmap;

// Sepia Effect

private Bitmap applySepiaEffect(Bitmap src) {

int width = src.getWidth();

int height = src.getHeight();

Bitmap sepiaBitmap = Bitmap.createBitmap(width, height, src.getConfig());


for (int x = 0; x < width; x++) {

for (int y = 0; y < height; y++) {

int pixel = src.getPixel(x, y);

int red = Color.red(pixel);

int green = Color.green(pixel);

int blue = Color.blue(pixel);

int tr = (int)(0.393 * red + 0.769 * green + 0.189 * blue);

int tg = (int)(0.349 * red + 0.686 * green + 0.168 * blue);

int tb = (int)(0.272 * red + 0.534 * green + 0.131 * blue);

sepiaBitmap.setPixel(x, y, Color.rgb(Math.min(tr, 255), Math.min(tg, 255), Math.min(tb, 255)));

return sepiaBitmap;

// More effects can be added similarly.

Step 5: Test Your Application

1. Run your application on an emulator or physical device.

2. Select an image from the gallery and apply the effects using the buttons.
EXPERIMENT 10:

AIM: Create an Android Application Using ImageSwitcher

Step 1: Set up a New Android Project

1. Open Android Studio.

2. Select New Project.

3. Choose Empty Activity and click Next.

4. Enter the project name as ImageSwitcherApp.

5. Choose your preferred programming language (Java or Kotlin).

6. Click Finish to create the project

Step 2: Modify the Layout File (XML)

1. Open the res/layout/activity_main.xml file.

2. Add an ImageSwitcher widget and a Button to switch between images.

CODE1:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

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">

<!-- ImageSwitcher -->

<ImageSwitcher

android:id="@+id/imageSwitcher"

android:layout_width="match_parent"

android:layout_height="300dp"

android:layout_marginTop="50dp"

android:layout_gravity="center"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"

android:inAnimation="@android:anim/fade_in"

android:outAnimation="@android:anim/fade_out"

/>

<!-- Button to change image -->

<Button

android:id="@+id/btnNext"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Next Image"

android:layout_marginTop="20dp"

app:layout_constraintTop_toBottomOf="@+id/imageSwitcher"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Add Images to the Drawable Folder

1. Add some sample images to the res/drawable folder. These will be the images that are
switched using the ImageSwitcher.

2. You can use images like image1.jpg, image2.jpg, etc.

Step 4: Modify the MainActivity Java/Kotlin File

1. Open MainActivity.java (or MainActivity.kt if using Kotlin).

2. Write code to handle switching images on button click.

CODE2:

package com.example.imageswitcherapp;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.ImageSwitcher;

import android.widget.ImageView;
import android.widget.ViewSwitcher;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

ImageSwitcher imageSwitcher;

Button btnNext;

int[] imageIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3};

int currentIndex = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

imageSwitcher = findViewById(R.id.imageSwitcher);

btnNext = findViewById(R.id.btnNext);

// Set factory for ImageSwitcher

imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

@Override

public View makeView() {

ImageView imageView = new ImageView(getApplicationContext());

imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

return imageView;

});

// Set the first image

imageSwitcher.setImageResource(imageIds[currentIndex]);
// Set button click listener to switch images

btnNext.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

currentIndex++;

if (currentIndex >= imageIds.length) {

currentIndex = 0;

imageSwitcher.setImageResource(imageIds[currentIndex]);

});

Step 5: Run the Application

1. Run the app on an emulator or physical device.

2. When the app starts, it should display the first image.

3. Click the Next Image button to switch to the next image in the sequence.

4. The ImageSwitcher will animate the transition between images.


EXPERIMENT 11:

AIM: Create an Android Application Using AlertDialog

Step 1: Set up a New Android Project

1. Open Android Studio.

2. Select New Project.

3. Choose Empty Activity and click Next.

4. Enter the project name as AlertDialogApp.

5. Choose your preferred programming language (Java or Kotlin).

6. Click Finish to create the project.

Step 2: Modify the Layout File (XML)

1. Open the res/layout/activity_main.xml file.

2. Add a button that will trigger the AlertDialog when clicked.

CODE1:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

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">

<!-- Button to show AlertDialog -->

<Button

android:id="@+id/btnShowDialog"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show AlertDialog"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Modify the MainActivity Java/Kotlin File

1. Open MainActivity.java (or MainActivity.kt if using Kotlin).

2. Implement the code to display the AlertDialog when the button is clicked.

CODE2:

package com.example.alertdialogapp;

import android.content.DialogInterface;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

Button btnShowDialog;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btnShowDialog = findViewById(R.id.btnShowDialog);

btnShowDialog.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {


showAlertDialog();

});

private void showAlertDialog() {

// Create the AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Alert Dialog");

builder.setMessage("Are you sure you want to proceed?");

// Set the positive button

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

// Do something when the user clicks Yes

Toast.makeText(MainActivity.this, "You clicked Yes", Toast.LENGTH_SHORT).show();

});

// Set the negative button

builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

// Do something when the user clicks No

dialog.dismiss();

Toast.makeText(MainActivity.this, "You clicked No", Toast.LENGTH_SHORT).show();

});

// Create and show the AlertDialog


AlertDialog dialog = builder.create();

dialog.show();

Step 4: Run the Application

1. Run the app on an emulator or physical device.

2. When the app starts, click the Show AlertDialog button.

3. A dialog will appear with the message "Are you sure you want to proceed?" and two
buttons: Yes and No.

4. Clicking Yes will display a toast message saying "You clicked Yes".

5. Clicking No will close the dialog and display a toast message saying "You clicked No".
EXPERIMENT 12:

AIM: Create an Android Application to Integrate Google Maps

1. Set Up a New Android Project

1. Open Android Studio and create a new project.

o Choose "Empty Activity" and click "Next."

o Name your project (e.g., MapIntegrationApp).

o Select "Java" or "Kotlin" as your programming language.

o Click "Finish."

2. Add Google Maps Dependency

1. Open the build.gradle file for your app module (usually located in app/build.gradle).

2. Add the following dependencies inside the dependencies block:

implementation 'com.google.android.gms:play-services-maps:18.0.0'

3. Obtain a Google Maps API Key

1. Go to the Google Cloud Console.

2. Create a new project or select an existing one.

3. Enable the Google Maps Android API:

o Go to the "API & Services" > "Library" section.

o Search for "Google Maps Android API" and enable it.

4. Generate an API key:

o Go to "Credentials" and click on "Create Credentials."

o Select "API key." Restrict the API key for use with your application as needed.

4. Configure Your App with the API Key

1. Open the AndroidManifest.xml file (usually located in src/main/AndroidManifest.xml).

2. Add the following permissions and metadata within the <manifest> tag:

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application

...>

<meta-data

android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>

<activity android:name=".MapsActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

</application>

1. Replace YOUR_API_KEY with the API key obtained earlier.

5. Create a Layout for the Map

1. Open the res/layout/activity_maps.xml file (create it if it doesn’t exist).

2. Add a MapView to the layout:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent">

<fragment

android:id="@+id/map"

android:name="com.google.android.gms.maps.SupportMapFragment"

android:layout_width="match_parent"

android:layout_height="match_parent" />

</RelativeLayout>

6. Implement the Map in Your Activity

1. Create a new activity (e.g., MapsActivity.java or MapsActivity.kt).

2. Implement the map setup:

// MapsActivity.java

package com.example.mapintegrationapp;

import android.os.Bundle;
import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;

import com.google.android.gms.maps.model.LatLngBounds;

import com.google.android.gms.maps.model.CameraPosition;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_maps);

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()

.findFragmentById(R.id.map);

mapFragment.getMapAsync(this);

@Override

public void onMapReady(@NonNull GoogleMap googleMap) {

mMap = googleMap;

// Add a marker in a location and move the camera

LatLng location = new LatLng(-34, 151); // Example coordinates


mMap.addMarker(new MarkerOptions().position(location).title("Marker in Sydney"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(location));

mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 12.0f));

7. Run Your Application

1. Build and run your app on an emulator or a physical device.

2. Ensure you have an internet connection and that location permissions are granted.
EXPERIMENT 13:

AIM: Create an Android Application To send SMS

1. Set Up a New Android Project

1. Open Android Studio and create a new project.

o Choose "Empty Activity" and click "Next."

o Name your project (e.g., SmsSenderApp).

o Select "Java" or "Kotlin" as your programming language.

o Click "Finish."

2. Add Permissions to AndroidManifest.xml

1. Open the AndroidManifest.xml file (usually located in src/main/AndroidManifest.xml).

2. Add the following permissions inside the <manifest> tag:

<uses-permission android:name="android.permission.SEND_SMS"/>

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

3. Create the Layout for Sending SMS

1. Open res/layout/activity_main.xml and design your layout. Add an EditText for the phone
number, another EditText for the message, and a Button to send the SMS:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<EditText

android:id="@+id/phoneNumberEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Phone Number"

android:inputType="phone"/>

<EditText

android:id="@+id/messageEditText"
android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Message"

android:layout_below="@id/phoneNumberEditText"

android:layout_marginTop="16dp"

android:inputType="textMultiLine"/>

<Button

android:id="@+id/sendSmsButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send SMS"

android:layout_below="@id/messageEditText"

android:layout_marginTop="16dp"/>

</RelativeLayout>

4. Implement SMS Sending Logic in Your Activity

1. Open MainActivity.java or MainActivity.kt and add the logic to send an SMS message:

// MainActivity.java

package com.example.smssenderapp;

import android.Manifest;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

private static final int SMS_PERMISSION_CODE = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

EditText phoneNumberEditText = findViewById(R.id.phoneNumberEditText);

EditText messageEditText = findViewById(R.id.messageEditText);

Button sendSmsButton = findViewById(R.id.sendSmsButton);

sendSmsButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String phoneNumber = phoneNumberEditText.getText().toString();

String message = messageEditText.getText().toString();

if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)

!= PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(MainActivity.this,

new String[]{Manifest.permission.SEND_SMS}, SMS_PERMISSION_CODE);

} else {

sendSMS(phoneNumber, message);

});

}
private void sendSMS(String phoneNumber, String message) {

try {

SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage(phoneNumber, null, message, null, null);

Toast.makeText(this, "SMS sent!", Toast.LENGTH_LONG).show();

} catch (Exception e) {

Toast.makeText(this, "SMS failed, please try again.", Toast.LENGTH_LONG).show();

e.printStackTrace();

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,


@NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == SMS_PERMISSION_CODE) {

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

sendSMS(((EditText) findViewById(R.id.phoneNumberEditText)).getText().toString(),

((EditText) findViewById(R.id.messageEditText)).getText().toString());

} else {

Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();

5. Run Your Application

1. Build and run your app on an emulator or physical device.

2. Enter a phone number and message and click the "Send SMS" button to send an SMS.
EXPERIMENT 14:

AIM: Create an Android Application To calling a number

1. Set Up a New Android Project

1. Open Android Studio and create a new project.

o Choose "Empty Activity" and click "Next."

o Name your project (e.g., CallApp).

o Select "Java" or "Kotlin" as your programming language.

o Click "Finish."

2. Add Permissions to AndroidManifest.xml

1. Open the AndroidManifest.xml file (usually located in src/main/AndroidManifest.xml).

2. Add the following permission inside the <manifest> tag:

<uses-permission android:name="android.permission.CALL_PHONE"/>

3. Create the Layout for Making a Call

1. Open res/layout/activity_main.xml and design your layout. Add an EditText for the phone
number and a Button to initiate the call:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<EditText

android:id="@+id/phoneNumberEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Phone Number"

android:inputType="phone"/>

<Button

android:id="@+id/callButton"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Call"

android:layout_below="@id/phoneNumberEditText"

android:layout_marginTop="16dp"/>

</RelativeLayout>

4. Implement the Call Logic in Your Activity

1. Open MainActivity.java or MainActivity.kt and add the logic to make a call:

// MainActivity.java

package com.example.callapp;

import android.Manifest;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;

import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

private static final int CALL_PERMISSION_CODE = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
EditText phoneNumberEditText = findViewById(R.id.phoneNumberEditText);

Button callButton = findViewById(R.id.callButton);

callButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String phoneNumber = phoneNumberEditText.getText().toString();

if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)

!= PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(MainActivity.this,

new String[]{Manifest.permission.CALL_PHONE}, CALL_PERMISSION_CODE);

} else {

makeCall(phoneNumber);

});

private void makeCall(String phoneNumber) {

Intent callIntent = new Intent(Intent.ACTION_CALL);

callIntent.setData(Uri.parse("tel:" + phoneNumber));

startActivity(callIntent);

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,


@NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == CALL_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

String phoneNumber = ((EditText)


findViewById(R.id.phoneNumberEditText)).getText().toString();

makeCall(phoneNumber);

} else {

Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();

5. Run Your Application

1. Build and run your app on an emulator or physical device.

2. Enter a phone number and click the "Call" button to initiate a call.
EXPERIMENT 15:

AIM: Create an Android Application To send E-mail

1. Set Up a New Android Project

1. Open Android Studio and create a new project.

o Choose "Empty Activity" and click "Next."

o Name your project (e.g., EmailSenderApp).

o Select "Java" or "Kotlin" as your programming language.

o Click "Finish."

2. Create the Layout for Sending an Email

1. Open res/layout/activity_main.xml and design your layout. Add EditText fields for the
recipient email, subject, and message body, and a Button to send the email:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<EditText

android:id="@+id/recipientEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Recipient Email"

android:inputType="textEmailAddress"/>

<EditText

android:id="@+id/subjectEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Subject"

android:layout_below="@id/recipientEditText"

android:layout_marginTop="16dp"/>
<EditText

android:id="@+id/messageEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Message"

android:layout_below="@id/subjectEditText"

android:layout_marginTop="16dp"

android:inputType="textMultiLine"

android:lines="5"

android:scrollbars="vertical"/>

<Button

android:id="@+id/sendEmailButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send Email"

android:layout_below="@id/messageEditText"

android:layout_marginTop="16dp"/>

</RelativeLayout>

3. Implement Email Sending Logic in Your Activity

1. Open MainActivity.java or MainActivity.kt and add the logic to handle the email sending
intent:

// MainActivity.java

package com.example.emailsenderapp;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

EditText recipientEditText = findViewById(R.id.recipientEditText);

EditText subjectEditText = findViewById(R.id.subjectEditText);

EditText messageEditText = findViewById(R.id.messageEditText);

Button sendEmailButton = findViewById(R.id.sendEmailButton);

sendEmailButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String recipient = recipientEditText.getText().toString();

String subject = subjectEditText.getText().toString();

String message = messageEditText.getText().toString();

if (recipient.isEmpty() || subject.isEmpty() || message.isEmpty()) {

Toast.makeText(MainActivity.this, "Please fill in all fields", Toast.LENGTH_SHORT).show();

return;

Intent intent = new Intent(Intent.ACTION_SENDTO);

intent.setData(Uri.parse("mailto:"));

intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient});


intent.putExtra(Intent.EXTRA_SUBJECT, subject);

intent.putExtra(Intent.EXTRA_TEXT, message);

if (intent.resolveActivity(getPackageManager()) != null) {

startActivity(intent);

} else {

Toast.makeText(MainActivity.this, "No email client found", Toast.LENGTH_SHORT).show();

});

4. Run Your Application

1. Build and run your app on an emulator or physical device.

2. Enter recipient email, subject, and message and click the "Send Email" button to initiate the
email.
EXPERIMENT 16:

AIM: Create an Android Application Using Database

1. Set Up a New Android Project

1. Open Android Studio and create a new project.

o Choose "Empty Activity" and click "Next."

o Name your project (e.g., DatabaseApp).

o Select "Java" or "Kotlin" as your programming language.

o Click "Finish."

2. Define the Database Schema

1. Create a new Java/Kotlin class for the SQLite database helper.

o Java: DatabaseHelper.java

package com.example.databaseapp;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mydatabase.db";

private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "mytable";

private static final String COLUMN_ID = "_id";

private static final String COLUMN_NAME = "name";

private static final String TABLE_CREATE =

"CREATE TABLE " + TABLE_NAME + " (" +

COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

COLUMN_NAME + " TEXT NOT NULL);";


public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(TABLE_CREATE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

onCreate(db);

3. Implement Database Operations

1. Create a Data Access Object (DAO) for CRUD operations.

o Java: DatabaseDAO.java

package com.example.databaseapp;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseDAO {

private SQLiteOpenHelper openHelper;

private SQLiteDatabase database;

public DatabaseDAO(Context context) {


this.openHelper = new DatabaseHelper(context);

public void open() {

this.database = openHelper.getWritableDatabase();

public void close() {

if (database != null) {

database.close();

public long insert(String name) {

ContentValues values = new ContentValues();

values.put("name", name);

return database.insert("mytable", null, values);

public Cursor getAll() {

return database.query("mytable", null, null, null, null, null, null);

public int update(long id, String name) {

ContentValues values = new ContentValues();

values.put("name", name);

return database.update("mytable", values, "_id = ?", new String[]{String.valueOf(id)});

public void delete(long id) {

database.delete("mytable", "_id = ?", new String[]{String.valueOf(id)});


}

4. Create the User Interface

1. Open res/layout/activity_main.xml and design your layout with EditText fields, Button
elements, and a ListView to display database records:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<EditText

android:id="@+id/nameEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Name"/>

<Button

android:id="@+id/addButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Add"

android:layout_below="@id/nameEditText"

android:layout_marginTop="16dp"/>

<ListView

android:id="@+id/listView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/addButton"

android:layout_marginTop="16dp"/>
</RelativeLayout>

5. Implement Main Activity Logic

1. Open MainActivity.java or MainActivity.kt and add the logic to handle user interactions and
database operations:

o Java: MainActivity.java

package com.example.databaseapp;

import android.database.Cursor;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText nameEditText;

private Button addButton;

private ListView listView;

private DatabaseDAO databaseDAO;

private ArrayAdapter<String> adapter;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditText);

addButton = findViewById(R.id.addButton);

listView = findViewById(R.id.listView);

databaseDAO = new DatabaseDAO(this);

databaseDAO.open();

adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

listView.setAdapter(adapter);

loadRecords();

addButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String name = nameEditText.getText().toString();

if (name.isEmpty()) {

Toast.makeText(MainActivity.this, "Name cannot be empty",


Toast.LENGTH_SHORT).show();

return;

long id = databaseDAO.insert(name);

if (id > 0) {

Toast.makeText(MainActivity.this, "Record added", Toast.LENGTH_SHORT).show();

loadRecords();

} else {

Toast.makeText(MainActivity.this, "Error adding record", Toast.LENGTH_SHORT).show();

});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

// Handle item click for update or delete

});

private void loadRecords() {

adapter.clear();

Cursor cursor = databaseDAO.getAll();

if (cursor.moveToFirst()) {

do {

String name = cursor.getString(cursor.getColumnIndex("name"));

adapter.add(name);

} while (cursor.moveToNext());

cursor.close();

@Override

protected void onDestroy() {

super.onDestroy();

databaseDAO.close();

6. Run Your Application

1. Build and run your app on an emulator or physical device.

2. Use the UI to add records, view them in the ListView, and interact with them.

You might also like