Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views63 pages

Android and Application Practical

The document outlines practical exercises for mobile application development using Android, covering the setup of the development environment, understanding various components like activities, services, and broadcast receivers, and creating simple applications. It includes detailed steps for installing Android Studio, configuring SDK and AVD, and designing user interfaces with different layouts and widgets. Additionally, it provides code examples for handling events and demonstrates the Android activity lifecycle.

Uploaded by

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

Android and Application Practical

The document outlines practical exercises for mobile application development using Android, covering the setup of the development environment, understanding various components like activities, services, and broadcast receivers, and creating simple applications. It includes detailed steps for installing Android Studio, configuring SDK and AVD, and designing user interfaces with different layouts and widgets. Additionally, it provides code examples for handling events and demonstrates the Android activity lifecycle.

Uploaded by

urvashishri556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Mobile Application Development Using Android Subject Code: 4350703

Practical No– 01
Set-up of Android development environment, managing AVD and understanding its
various components.

Android development environment:

Step 1: Install Android Studio


Download Android Studio from the website: https://developer.android.com/studio Run
the downloaded installer and follow the installation wizard instructions.
During the installation, select the components that we want to install, such as the Android SDK,
emulator, and development tools.
Step 2: Launch Android Studio
After the installation is complete, launch Android Studio.
Step 3: Configure SDK and AVD Manager
On the Android Studio Welcome screen, click on "Configure" in the bottom-right corner and
select "SDK Manager."
The SDK Manager allows us to install SDK components, platform versions, and system images
for different device configurations.
Step 4: Install SDK Platforms and System Images
In the SDK Platforms tab, install the Android versions (API levels) that we want to target in our
app. For example, Android 11 (API 30).
Step 5: Create an AVD (Android Virtual Device)
After installing the necessary SDK components, click on "AVD Manager".
In the AVD Manager, click "Create Virtual Device."
Choose the device type we want to emulate (e.g., Pixel 4) and click "Next."
Select a system image for the virtual device and click "Next."
Configure the AVD properties (e.g., device orientation, scale, RAM, and storage) and click
"Finish" to create the AVD.
Step 6: Run the AVD
Back in the AVD Manager, click the green "Play" button next to the AVD we created to start the
virtual device.
The AVD will start up, and the Android system running on the virtual device.
Step 7: Use AVD for Testing
In Android Studio, open Android project.On the toolbar, select AVD from the device dropdown
menu. Click the "Run" button to run app on the selected AVD.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 1


Mobile Application Development Using Android Subject Code: 4350703

Practical No– 02
Understanding of Various Components available in Android Application.
Android applications are built using various components that interact with each other to provide
the desired functionality and user experience.
Activities: An activity represents a single screen with a user interface. It is the most
fundamental component of an Android app and is responsible for interacting with the user. An
application may consist of one or multiple activities. Each activity extends the Activity class
and typically corresponds to a specific user interaction.
Fragments: Fragments are modular sections of an activity that can be combined and reused
across multiple activities. They are useful for creating responsive user interfaces, especially on
devices with varying screen sizes. Fragments extend the Fragment class and are managed by
activities.
Services: A service is a component that runs in the background, independent of any user
interface. It performs long-running operations or handles tasks that should continue to execute
even when app is not in the foreground. Services can be used to play music, download data, or
handle network transactions.
Broadcast Receivers: A broadcast receiver is a component that listens for and responds to
system-wide broadcasts. These broadcasts can be sent by the Android system or other apps.
Broadcast receivers allow your app to respond to events, such as incoming SMS messages,
network connectivity changes, or battery status updates.
Content Providers: A content provider allows the app to share data with other apps securely. It
acts as an interface to access and manage the app's data, which can be stored in a database, file,
or any other data source. Content providers enable inter-app data sharing, allowing other apps to
read or modify the data based on defined permissions.
Intents: Intents are messaging objects used to communicate between components within an app
or between different apps. They facilitate starting activities, services, or broadcasting events.
Intents can carry data along with them to pass information between components.
Layouts: Android uses XML-based layout files to define the user interface of an activity or
fragment. These layout files specify how different UI elements are arranged and displayed on
the screen.
Resources: Android apps use resources such as strings, colors, styles, and images. These
resources are kept separately from the code, allowing for easy localization and management.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 2


Mobile Application Development Using Android Subject Code: 4350703

Manifest File: The AndroidManifest.xml file contains important information about the app,
such as the app's package name, components, permissions required, and hardware features used.
It acts as a configuration file for the app.

Gradle Build System: Gradle is used to manage the build process of an Android app. It defines
dependencies, compiles code, and packages the app for distribution.

Practical No– 03
Develop a “Hello World” Application in Android and understand the structure of an
Android Application. activity_main.xml

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 3


Mobile Application Development Using Android Subject Code: 4350703

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="24sp" />
</LinearLayout>

Practical No– 04

AIM:- Develop Android Application to demonstrate methods of Activity Life Cycle.

MainActivity.java

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 4


Mobile Application Development Using Android Subject Code: 4350703

import android.os.Bundle; import


android.app.Activity; import
android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Toast.makeText(MainActivity.this,"onCreate method
called",Toast.LENGTH_LONG).show();
}
@Override
protected void onStart()
{
super.onStart();
Toast.makeText(MainActivity.this,"onStart method
called",Toast.LENGTH_LONG).show();
}
@Override
protected void onResume()
{
super.onResume();
Toast.makeText(MainActivity.this,"onResume method
called",Toast.LENGTH_LONG).show();
}

@Override
protected void onRestart()
{
super.onRestart();
Toast.makeText(MainActivity.this,"onRestart method
called",Toast.LENGTH_LONG).show();
}
@Override
protected void onStop()

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 5


Mobile Application Development Using Android Subject Code: 4350703

{
super.onStop();
Toast.makeText(MainActivity.this,"onStop method
called",Toast.LENGTH_LONG).show();
}
@Override
protected void onPause()
{
super.onPause();
Toast.makeText(MainActivity.this,"onPause method
called",Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy()
{
super.onDestroy();
Toast.makeText(MainActivity.this,"onDestroy method
called",Toast.LENGTH_LONG).show();
}

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

Practical No– 05

AIM:- Design Android Activities using LinearLayout, RelativeLayout, GridView,


FrameLayout, and ConstraintLayout.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 6


Mobile Application Development Using Android Subject Code: 4350703

LinearLayout:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="This is a LinearLayout"
android:textSize="20sp" /> <!-- Add
more views as needed -->
</LinearLayout>

RelativeLayout:

activity_main.xml
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a RelativeLayout"
android:textSize="20sp" />
</RelativeLayout>

GridView:

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

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 7


Mobile Application Development Using Android Subject Code: 4350703

xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" android:verticalSpacing="8dp"
android:horizontalSpacing="8dp" android:padding="8dp"
android:gravity="center" />

FrameLayout:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:contentDescription="Image in FrameLayout" />
</FrameLayout>

ConstraintLayout:

activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 8


Mobile Application Development Using Android Subject Code: 4350703

android:text="This is a ConstraintLayout"
android:textSize="20sp"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 9


Mobile Application Development Using Android Subject Code: 4350703

Practical No– 06

AIM:- Design various Activities using different Layouts and available Widgets
(TextView, EditText, Button, RadioButton, CheckBox, ImageButton, ToggleButton,
TimePicker, DatePicker, ProgressBar, ImageView) to make the user-friendly GUI.

1. MainActivity (Linear Layout with EditText and Button):

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

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

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />

</LinearLayout>

2. SecondActivity (Relative Layout with CheckBox, RadioButton, and ToggleButton):

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

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 10


Mobile Application Development Using Android Subject Code: 4350703

<CheckBox
android:id="@+id/chkSound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable Sound" />

<RadioButton
android:id="@+id/radioOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/chkSound"
android:text="Option 1" />

<RadioButton
android:id="@+id/radioOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioOption1"
android:text="Option 2" />

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioOption2"
android:textOff="Off"
android:textOn="On" />

</RelativeLayout>

3. ThirdActivity (Constraint Layout with TimePicker and DatePicker):

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 11


Mobile Application Development Using Android Subject Code: 4350703

<TimePicker
android:id="@+id/timePicker"
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="20dp" />

<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/timePicker"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. FourthActivity (Frame Layout with ProgressBar and ImageView):

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


<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />

<ImageView android:id="@+id/imageView"
android:layout_width="wrap_content"

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 12


Mobile Application Development Using Android Subject Code: 4350703

android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:contentDescription="Sample Image1"
android:visibility="gone" />
</FrameLayout>
Practical No– 07

AIM:- Develop code to demonstrate different ways of Handling different events


(onClick, onLongClick etc.) over Button, EditText etc. to perform action in Android
application at run-time.

import android.os.Bundle; import


android.app.Activity; import
android.view.Menu; import
android.view.View; import
android.widget.Button; import
android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText et1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

et1=(EditText)findViewById(R.id.editText1);
b1=(Button)findViewById(R.id.button1);

b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) { // TODO Auto-generated
method stub
String s=et1.getText().toString();
Toast t=Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 13


Mobile Application Development Using Android Subject Code: 4350703

t.show();
}
});

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

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 14


Mobile Application Development Using Android Subject Code: 4350703

Practical No– 08

AIM:- Develop code to demonstrate Event handling of CheckBox and RadioButton


selection.

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Me" />

<RadioButton
android:id="@+id/radioOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />

<RadioButton
android:id="@+id/radioOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />

</LinearLayout>

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 15


Mobile Application Development Using Android Subject Code: 4350703

MainActivity.java

import android.os.Bundle; import


android.view.View; import
android.widget.CheckBox; import
android.widget.CompoundButton; import
android.widget.RadioButton; import
android.widget.RadioGroup; import
android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private CheckBox checkBox;


private RadioButton radioOption1, radioOption2;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

checkBox = findViewById(R.id.checkBox);
radioOption1 = findViewById(R.id.radioOption1);
radioOption2 = findViewById(R.id.radioOption2);

checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
showToast("CheckBox is checked!");
} else {
showToast("CheckBox is unchecked!");
}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 16


Mobile Application Development Using Android Subject Code: 4350703

}
});

RadioGroup radioGroup = findViewById(R.id.radioGroup);


radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) { case R.id.radioOption1:
showToast("Option 1 is selected!"); break; case
R.id.radioOption2: showToast("Option 2 is selected!");
break;
}
}
});
}

private void showToast(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 17


Mobile Application Development Using Android Subject Code: 4350703

Practical No– 09

AIM:- Develop code to navigate between different activities and pass the data from one
activity to other activity using Intent.

Mainactivity.java import
android.os.Bundle; import
android.app.Activity; import
android.content.Intent;
//import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) { // TODO Auto-generated
method stub
Intent i= new Intent(getApplicationContext(),Second.class);
startActivity(i);
}
});
}
}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 18


Mobile Application Development Using Android Subject Code: 4350703

Second.java mport
android.os.Bundle; import
android.app.Activity;
import android.view.Menu;

public class Second extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}

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

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 19


Mobile Application Development Using Android Subject Code: 4350703

Practical No– 10
AIM:- Develop an android application to store data locally using Shared Preferences and
access-modify in different activities.

Create two activities:


MainActivity (Default activity)
SettingsActivity

Implement the layouts for both activities. activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<Button
android:id="@+id/btnSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Settings" />

</LinearLayout>

activity_settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp" android:orientation="vertical">

<EditText

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 20


Mobile Application Development Using Android Subject Code: 4350703

android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="Enter your
name" />

<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="Enter
your email" />

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

</LinearLayout>

Implement the logic for storing and accessing data using Shared Preferences in the
MainActivity and SettingsActivity:

MainActivity.java:

import android.content.Intent; import


android.content.SharedPreferences;
import android.os.Bundle; import
android.view.View; import
android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static final String PREF_NAME = "MyPrefs";


private Button btnSettings;

@Override

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 21


Mobile Application Development Using Android Subject Code: 4350703

protected void onCreate(Bundle savedInstanceState)


{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnSettings = findViewById(R.id.btnSettings); btnSettings.setOnClickListener(new


View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
});
}
}

SettingsActivity.java: import
android.content.SharedPreferences;
import android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {

private static final String PREF_NAME =


"MyPrefs"; private EditText etName, etEmail;
private Button btnSave;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);

etName = findViewById(R.id.etName);
etEmail = findViewById(R.id.etEmail);
btnSave = findViewById(R.id.btnSave);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 22


Mobile Application Development Using Android Subject Code: 4350703

// Load the saved data from Shared Preferences


SharedPreferences preferences = getSharedPreferences(PREF_NAME,
MODE_PRIVATE);
String savedName = preferences.getString("name", "");
String savedEmail = preferences.getString("email", ""); etName.setText(savedName);
etEmail.setText(savedEmail);

btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Save the data to Shared Preferences
SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME,
MODE_PRIVATE).edit();
editor.putString("name", etName.getText().toString());
editor.putString("email", etEmail.getText().toString()); editor.apply();
finish(); // Close the activity after saving
}
});
}
}

Add both activities to the AndroidManifest.xml file:

xml Copy
code
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-
filter>
</activity>
<activity android:name=".SettingsActivity" />

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 23


Mobile Application Development Using Android Subject Code: 4350703

Practical No– 11
Develop the code to implement the ListView and the Spinner views, perform add, update,
remove items operations and implement the item selection event handling over ListView
and Spinner for appropriate example.

Program -1
To implement a ListView with add, update, and remove item operations along with item
selection event handling in Android.

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"
android:onClick="addItem" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Item"
android:onClick="updateItem" />

<Button

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 24


Mobile Application Development Using Android Subject Code: 4350703

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove Item"
android:onClick="removeItem" />

</RelativeLayout>
MainActivity.java
import android.os.Bundle; import
android.view.View; import
android.widget.AdapterView; import
android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private ListView listView;


private ArrayList<String> items;
private ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = findViewById(R.id.listView);
items = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);

// Set the adapter to the ListView


listView.setAdapter(adapter);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 25


Mobile Application Development Using Android Subject Code: 4350703

// Add sample data to the list


items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
adapter.notifyDataSetChanged();

// Handle item selection


listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = items.get(position);
Toast.makeText(MainActivity.this, "Selected item: " + selectedItem,
Toast.LENGTH_SHORT).show();
}
});
}

// Add new item to the list


public void addItem(View view) {
items.add("New Item");
adapter.notifyDataSetChanged();
}

// Update the selected item in the list public void


updateItem(View view) { int selectedPosition =
listView.getCheckedItemPosition(); if (selectedPosition !
= ListView.INVALID_POSITION) { String
updatedItem = "Updated Item";
items.set(selectedPosition, updatedItem);
adapter.notifyDataSetChanged(); } else {
Toast.makeText(this, "Select an item to update", Toast.LENGTH_SHORT).show();
}
}

// Remove the selected item from the list public void


removeItem(View view) { int selectedPosition =
listView.getCheckedItemPosition(); if (selectedPosition !
= ListView.INVALID_POSITION) {

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 26


Mobile Application Development Using Android Subject Code: 4350703

items.remove(selectedPosition);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(this, "Select an item to remove", Toast.LENGTH_SHORT).show();
}
}
}

Program -2
To implement a SpinnerView with add, update, and remove item operations along with item
selection event handling in Android

 In the layout XML file (activity_spinner.xml), add a Spinner, EditText, and three Buttons
(Add, Update, and Remove) to allow user interaction.

Java Code

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.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class SpinnerActivity extends AppCompatActivity


{ private Spinner spinner;
private ArrayAdapter<String> spinnerAdapter;
private ArrayList<String> items; private
EditText editText; private Button addButton;

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 27


Mobile Application Development Using Android Subject Code: 4350703

private Button updateButton; private Button


removeButton;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);

// Initialize views
spinner = findViewById(R.id.spinner);
editText = findViewById(R.id.edit_text);
addButton = findViewById(R.id.add_button);
updateButton = findViewById(R.id.update_button);
removeButton =
findViewById(R.id.remove_button);

// Initialize data
items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");

// Initialize spinner adapter


spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
items);

spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
;
spinner.setAdapter(spinnerAdapter);

// Handle item selection event


spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
Toast.makeText(SpinnerActivity.this, "Selected: " + selectedItem,
Toast.LENGTH_SHORT).show();
}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 28


Mobile Application Development Using Android Subject Code: 4350703

@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

// Handle add button click


addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newItem = editText.getText().toString().trim();
if (!newItem.isEmpty()) { items.add(newItem);
spinnerAdapter.notifyDataSetChanged();
editText.getText().clear();
}
}
});

// Handle update button click


updateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedItemPosition = spinner.getSelectedItemPosition();
String updatedItem = editText.getText().toString().trim();
if (selectedItemPosition != AdapterView.INVALID_POSITION &&
!updatedItem.isEmpty()) {
items.set(selectedItemPosition, updatedItem);
spinnerAdapter.notifyDataSetChanged();
editText.getText().clear();
}
}
});

// Handle remove button click


removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 29


Mobile Application Development Using Android Subject Code: 4350703

int selectedItemPosition = spinner.getSelectedItemPosition();


if (selectedItemPosition != AdapterView.INVALID_POSITION) {
items.remove(selectedItemPosition);
spinnerAdapter.notifyDataSetChanged();
editText.getText().clear();
}
}
});
}
}

Practical No– 12
Develop the code to manage Permission using Manifest file and run time from Activity,
and toggle state of WiFi and Bluetooth.

Program – 1

To manage permissions in Android, you need to declare permissions in the


AndroidManifest.xml file and request them at runtime in the Activity when needed.

 Add Permissions to AndroidManifest.xml: Open your AndroidManifest.xml file and add


the necessary permissions. For this example, let's add the
"READ_EXTERNAL_STORAGE" permission to read external storage.

Manifest.xml code

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">

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

<application

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 30


Mobile Application Development Using Android Subject Code: 4350703

<!-- Your application details here -->


</application>

</manifest>

Java code

import android.Manifest;
import android.content.pm.PackageManager; import
android.os.Bundle;
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 YourActivity extends AppCompatActivity {


private static final int REQUEST_READ_EXTERNAL_STORAGE = 1;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Check if the required permission is granted or not


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Permission is already granted
// You can perform the tasks that require this permission here
// For example, access the external storage
} else {
// Permission is not granted
// Request the permission from the user
ActivityCompat.requestPermissions(this,

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 31


Mobile Application Development Using Android Subject Code: 4350703

new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_READ_EXTERNAL_STORAGE);
}
}

// Handle the permission request result


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission is granted
// Perform the tasks that require this permission here
// For example, access the external storage
} else {
// Permission is denied
// You can handle this situation here, e.g., show an explanation or disable functionality
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}

 In this code, we first check if the permission is already granted using


ContextCompat.checkSelfPermission().
 If it's not granted, we request the permission using
ActivityCompat.requestPermissions().
 The user will see a dialog asking for permission, and the result will be handled in
onRequestPermissionsResult().

Program – 2

Implement toggle state of WiFi and Bluetooth in android.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 32


Mobile Application Development Using Android Subject Code: 4350703

 To implement the toggle state of WiFi and Bluetooth in an Android application, you can
use the WifiManager and BluetoothAdapter classes provided by the Android
framework.
 Add necessary permissions to the AndroidManifest.xml file: Ensure that you have the
following permissions in your AndroidManifest.xml to control WiFi and Bluetooth:

AndroidManifest.xml

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


<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Java code

import android.bluetooth.BluetoothAdapter;
import android.net.wifi.WifiManager; import
android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {

private WifiManager wifiManager;


private BluetoothAdapter bluetoothAdapter;
private Switch wifiSwitch, bluetoothSwitch;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

wifiManager = (WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

wifiSwitch = findViewById(R.id.wifiSwitch);
bluetoothSwitch = findViewById(R.id.bluetoothSwitch);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 33


Mobile Application Development Using Android Subject Code: 4350703

// Set initial state of switches


wifiSwitch.setChecked(wifiManager.isWifiEnabled());
bluetoothSwitch.setChecked(bluetoothAdapter.isEnabled());

wifiSwitch.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toggleWiFi(isChecked);
}
});

bluetoothSwitch.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toggleBluetooth(isChecked);
}
});
}

private void toggleWiFi(boolean enable) {


if (enable) {
wifiManager.setWifiEnabled(true);
} else {
wifiManager.setWifiEnabled(false);
}
}

private void toggleBluetooth(boolean enable) {


if (enable) {
bluetoothAdapter.enable();
} else {
bluetoothAdapter.disable();
}
}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 34


Mobile Application Development Using Android Subject Code: 4350703

activity_main.xml

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

<Switch
android:id="@+id/wifiSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WiFi"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />

<Switch
android:id="@+id/bluetoothSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bluetooth"
android:layout_below="@id/wifiSwitch"
android:layout_alignParentStart="true" />

</RelativeLayout>

Practical No – 13
Develop android applications to demonstrate user interaction with the application using
Options Menu, Context Menu and Popup Menu.

Program – 1
To demonstrate user interaction with an Android application using the Options Menu

MainActivity.java

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 35


Mobile Application Development Using Android Subject Code: 4350703

import android.os.Bundle; import


android.view.Menu; import
android.view.MenuItem; 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);
}

// Inflate the options menu


@Override public boolean
onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}

// Handle option menu item clicks


@Override
public boolean onOptionsItemSelected(MenuItem item)
{ switch (item.getItemId()) { case
R.id.menu_option_1:
showToast("Option 1 selected");
return true; case
R.id.menu_option_2:
showToast("Option 2 selected");
return true; case
R.id.menu_option_3:
showToast("Option 3 selected");
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 36


Mobile Application Development Using Android Subject Code: 4350703

private void showToast(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

options_menu.xml
<!-- options_menu.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_option_1"
android:title="Option 1"
android:orderInCategory="100"
android:showAsAction="never" />
<item
android:id="@+id/menu_option_2"
android:title="Option 2"
android:orderInCategory="101"
android:showAsAction="never" />
<item
android:id="@+id/menu_option_3"
android:title="Option 3"
android:orderInCategory="102"
android:showAsAction="never" />
</menu>

Program – 2
To demonstrate user interaction with an Android application using the context Menu.

activity_main.xml
<!-- activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 37


Mobile Application Development Using Android Subject Code: 4350703

android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical"
android:padding="16dp" tools:context=".MainActivity">

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

context_menu.xml
<!-- context_menu.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_edit"
android:title="Edit" />
<item
android:id="@+id/action_delete"
android:title="Delete" />
</menu>

MainActivity.java
import android.os.Bundle; import
android.view.ContextMenu; import
android.view.MenuItem; import
android.view.View; import
android.widget.AdapterView; import
android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 38


Mobile Application Development Using Android Subject Code: 4350703

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private ListView listView;


private ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = findViewById(R.id.listView);

// Sample data for the ListView


String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};

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


listView.setAdapter(adapter);

// Register the ListView for a context menu


registerForContextMenu(listView);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{ super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
}

@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
// Handle context menu item selection
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)
item.getMenuInfo();

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 39


Mobile Application Development Using Android Subject Code: 4350703

int position = info.position;


String selectedItem = adapter.getItem(position);

switch (item.getItemId()) {
case R.id.action_edit: //
Perform the edit action
Toast.makeText(this, "Edit: " + selectedItem, Toast.LENGTH_SHORT).show();
return true; case R.id.action_delete: // Perform the delete action
adapter.remove(selectedItem); adapter.notifyDataSetChanged();
Toast.makeText(this, "Deleted: " + selectedItem, Toast.LENGTH_SHORT).show();
return true; default:
return super.onContextItemSelected(item);
}
}
}

 Now, run the application on an Android emulator or a physical device.


 You should see a list of items.
 Long-press on an item and the context menu will appear with "Edit" and "Delete"
options.
 Selecting these options will display a toast message and delete the item from the list,
respectively.

Program – 3
To demonstrate user interaction with an Android application using the Popup Menu.

activity_main.xml

<!-- activity_main.xml -->


<RelativeLayout 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" android:padding="16dp"
tools:context=".MainActivity">

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 40


Mobile Application Development Using Android Subject Code: 4350703

<Button
android:id="@+id/btnShowPopup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu"
android:layout_centerInParent="true" />

<TextView
android:id="@+id/tvSelectedOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnShowPopup"
android:layout_centerHorizontal="true"
android:paddingTop="16dp" />

</RelativeLayout>

MainActivity.java

import android.os.Bundle; import


android.view.MenuItem; import
android.view.View; import
android.widget.Button; import
android.widget.PopupMenu; import
android.widget.TextView; import
androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private Button btnShowPopup;


private TextView tvSelectedOption;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 41


Mobile Application Development Using Android Subject Code: 4350703

btnShowPopup = findViewById(R.id.btnShowPopup);
tvSelectedOption = findViewById(R.id.tvSelectedOption);

btnShowPopup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create and show the Popup Menu
showPopupMenu();
}
});
}

private void showPopupMenu() {


// Create a PopupMenu object with the anchor view (the button) as the first parameter
PopupMenu popupMenu = new PopupMenu(this, btnShowPopup);

// Inflate the menu layout from the XML resource file


popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

// Set a click listener on the Popup Menu items


popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item) {
// Handle the selected item here
String selectedOption = item.getTitle().toString();
tvSelectedOption.setText("Selected: " + selectedOption); return true;
}
});

// Show the Popup Menu


popupMenu.show();
}
}

popup_menu.xml

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 42


Mobile Application Development Using Android Subject Code: 4350703

<!-- res/menu/popup_menu.xml -->


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/option1"
android:title="Option 1" />
<item
android:id="@+id/option2"
android:title="Option 2" />
<item
android:id="@+id/option3"
android:title="Option 3" />
</menu>

 Build and run the application on an Android emulator or physical device.


 When you click the "Show Popup Menu" button, the Popup Menu will appear with the
three options ("Option 1," "Option 2," and "Option 3").
 When you select an option from the menu, the selected option will be displayed below
the button in the TextView.

Practical – 14

Develop Android Applications to demonstrate different AlertDialogs and the Custom


Dialog.

Program – 1

To demonstrate AlertDialog in Android applications

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 43


Mobile Application Development Using Android Subject Code: 4350703

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/btnShowDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog" />
</LinearLayout>

MainActivity.java

import android.content.DialogInterface;
import android.os.Bundle; import
android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 44


Mobile Application Development Using Android Subject Code: 4350703

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


btnShowDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{ showAlertDialog();
}
});
}

private void showAlertDialog() {


// Basic AlertDialog new
AlertDialog.Builder(this) .set
Title("Basic AlertDialog")
.setMessage("This is a basic AlertDialog.")
.setPositiveButton("OK", null)
.show();

// Confirmation AlertDialog
new AlertDialog.Builder(this)
.setTitle("Confirmation AlertDialog")
.setMessage("Do you want to proceed?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Code to handle positive button click
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Code to handle negative button click
}
})
.show();

// List AlertDialog

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 45


Mobile Application Development Using Android Subject Code: 4350703

final String[] items = {"Item 1", "Item 2", "Item 3"};


new AlertDialog.Builder(this)
.setTitle("List AlertDialog")
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Code to handle item selection
}
})
.show();
}
}

Program – 2

To demonstrate Custom Dialog in Android applications.

custom_dialog_layout.xml

<!-- custom_dialog_layout.xml -->


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" android:padding="16dp">

<TextView
android:id="@+id/dialogTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Custom Dialog"
android:textSize="18sp"
android:textColor="@android:color/black"
android:gravity="center"/>

<!-- Add other views as per your requirement -->

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 46


Mobile Application Development Using Android Subject Code: 4350703

<Button
android:id="@+id/dialogButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Close"
android:textColor="@android:color/white"
android:background="@drawable/button_background"/>

</LinearLayout>

 Create a new Java or Kotlin class that extends the Dialog class to create a custom
dialog.

Java Code:

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class CustomDialog extends Dialog {

private String title;


private OnDialogButtonClickListener onDialogButtonClickListener;

public CustomDialog(Context context, String title) {


super(context); this.title = title;
}

public void setOnDialogButtonClickListener(OnDialogButtonClickListener listener)


{ this.onDialogButtonClickListener = listener;
}

@Override

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 47


Mobile Application Development Using Android Subject Code: 4350703

protected void onCreate(Bundle savedInstanceState)


{ super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog_layout);

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


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

dialogTitle.setText(title);

dialogButton.setOnClickListener(v -> {
if (onDialogButtonClickListener != null) {
onDialogButtonClickListener.onDialogButtonClick();
}
dismiss();
});
}

public interface OnDialogButtonClickListener {


void onDialogButtonClick();
}
}

 Use the Custom Dialog in your activity: In your activity, use the custom dialog class
to show the dialog when needed. You can trigger the custom dialog to appear when a
button is clicked

Java Code:

import android.os.Bundle; import


android.view.View;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 48


Mobile Application Development Using Android Subject Code: 4350703

protected void onCreate(Bundle savedInstanceState)


{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.showCustomDialogButton).setOnClickListener(v ->
showCustomDialog());
}

private void showCustomDialog() {


CustomDialog customDialog = new CustomDialog(this, "Custom Dialog Example");
customDialog.setOnDialogButtonClickListener(() -> {
// Handle button click action
// For example, perform some operation or close the dialog
});
customDialog.show();
}
}

 In this example, when the button with the ID showCustomDialogButton is clicked, the
custom dialog will be displayed with the provided title.
 The OnDialogButtonClickListener interface allows you to handle button click actions
inside the custom dialog.
 Remember to replace R.layout.activity_main with your activity's layout file, and make
sure to have the custom dialog layout XML available in the res/layout directory.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 49


Mobile Application Development Using Android Subject Code: 4350703

Practical No – 15

Develop Android Application for local database connectivity and performing basic
database operations (select, insert, update, delete) using SQLiteDatabase and
SQLiteOpenHelper Classes.

1. In the XML layout file (e.g., activity_main.xml), create the necessary UI elements like
EditText and Buttons to perform database operations.
2. Create a new Java class called DatabaseHelper. This class will extend
SQLiteOpenHelper and handle creating and managing the database.

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 =
"my_database"; private static final int DATABASE_VERSION =
1;

private static final String TABLE_NAME = "my_table";


private static final String COLUMN_ID = "_id"; private
static final String COLUMN_NAME = "name";
// Add other columns as needed

private static final String CREATE_TABLE_QUERY = "CREATE TABLE " +


TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT NOT NULL);";

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 50


Mobile Application Development Using Android Subject Code: 4350703

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int


newVersion) { db.execSQL("DROP TABLE IF EXISTS " +
TABLE_NAME); onCreate(db);
}
}

MainActivity.java

import android.content.ContentValues; import


android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 implements View.OnClickListener {


private DatabaseHelper databaseHelper; private EditText nameEditText;
private Button insertButton, selectButton, updateButton, deleteButton;

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 51


Mobile Application Development Using Android Subject Code: 4350703

databaseHelper = new DatabaseHelper(this);

nameEditText = findViewById(R.id.editTextName);
insertButton = findViewById(R.id.buttonInsert); selectButton
= findViewById(R.id.buttonSelect); updateButton =
findViewById(R.id.buttonUpdate); deleteButton =
findViewById(R.id.buttonDelete);

insertButton.setOnClickListener(this);
selectButton.setOnClickListener(this);
updateButton.setOnClickListener(this);
deleteButton.setOnClickListener(this); }

@Override
public void onClick(View v) {
switch (v.getId()) { case
R.id.buttonInsert:
insertData();
break; case
R.id.buttonSelect:
selectData();
break; case
R.id.buttonUpdate:
updateData();
break; case
R.id.buttonDelete:
deleteData();
break;
}
}

private void insertData() {


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

if (!name.isEmpty()) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 52


Mobile Application Development Using Android Subject Code: 4350703

ContentValues values = new ContentValues();


values.put(DatabaseHelper.COLUMN_NAME, name);

long rowId = db.insert(DatabaseHelper.TABLE_NAME, null, values);

if (rowId != -1) {
Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to insert data", Toast.LENGTH_SHORT).show();
}

db.close();
}}
priva
te
void
selec
tData
() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();

Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, null, null, null, null, null, null);

StringBuilder data = new StringBuilder();


while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID));
String name =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));

data.append("ID: ").append(id).append(", Name: ").append(name).append("\n");


}

cursor.close();
db.close();

Toast.makeText(this, data.toString(), Toast.LENGTH_SHORT).show();


}

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 53


Mobile Application Development Using Android Subject Code: 4350703

private void updateData() {


// Implement update operation
}

private void deleteData() {


// Implement delete operation
}
}

Practical No – 17

Develop an Android Application to demonstrate the use of RecyclerView and CardView


for displaying list of items with multiple information.

Note: target a minimum SDK version that supports RecyclerView and CardView (at least API
level 21).

1. In your app's build.gradle file, add the following dependencies:

implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'

2. Create a model class to represent the items that will be displayed in the list.

public class Item { private


String title; private String
description; // Add more
fields as needed

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 54


Mobile Application Development Using Android Subject Code: 4350703

public Item(String title, String description)


{ this.title = title;
this.description = description;
}

// Create getters and setters as needed


}

3. Create an adapter class that extends RecyclerView.Adapter to handle the item list and
bind the data to the CardView layout.

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {


private List<Item> itemList;

public ItemAdapter(List<Item> itemList) {


this.itemList = itemList;
}

@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,
parent, false);
return new ItemViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
Item item = itemList.get(position); holder.titleTextView.setText(item.getTitle());
holder.descriptionTextView.setText(item.getDescription());
// Bind more data to the CardView as needed
}

@Override public int


getItemCount() { return
itemList.size();

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 55


Mobile Application Development Using Android Subject Code: 4350703

public static class ItemViewHolder extends RecyclerView.ViewHolder {


TextView titleTextView;
TextView descriptionTextView;
// Add more views from your CardView layout

public ItemViewHolder(View itemView) {


super(itemView);
titleTextView = itemView.findViewById(R.id.titleTextView);
descriptionTextView = itemView.findViewById(R.id.descriptionTextView);
// Initialize other views from your CardView layout
}
}
}

4. Create the layout file for your RecyclerView activity (e.g., activity_main.xml) with a
RecyclerView.

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

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

5. Create the layout file for the CardView item (e.g., item_layout.xml) that will display the
information for each item in the list. Customize this layout as per your requirements.

<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView


xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 56


Mobile Application Development Using Android Subject Code: 4350703

android:layout_margin="8dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"/>

<TextView
android:id="@+id/descriptionTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"/>
<!-- Add more views for other information -->

</LinearLayout>

</androidx.cardview.widget.CardView>

6. In the MainActivity.java, initialize the RecyclerView, create a list of items, and set up the
RecyclerView with the custom adapter:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

RecyclerView recyclerView = findViewById(R.id.recyclerView);


recyclerView.setLayoutManager(new LinearLayoutManager(this));

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 57


Mobile Application Development Using Android Subject Code: 4350703

List<Item> itemList = createItemList(); // Replace this with your own logic to create
the list of items
ItemAdapter itemAdapter = new ItemAdapter(itemList);
recyclerView.setAdapter(itemAdapter);
}

private List<Item> createItemList() {


// Replace this with your own logic to create a list of items
List<Item> itemList = new ArrayList<>(); itemList.add(new
Item("Item 1", "Description for Item 1")); itemList.add(new
Item("Item 2", "Description for Item 2"));
// Add more items as needed
return itemList;
}
}

Practical No – 18

Develop a simple application to display “Hello <Application Name>” using Kotlin

1. Create a new Kotlin project in your preferred IDE.


2. If you're using IntelliJ IDEA or Android Studio, you can create a new Kotlin project by
selecting "File" > "New" > "Project" > "Kotlin" > "Kotlin JVM."
3. In the main Kotlin file (usually named "Main.kt"), add the following code:

Main.kt

fun main()

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 58


Mobile Application Development Using Android Subject Code: 4350703

{
val applicationName = "My Simple Kotlin App"
println("Hello $applicationName") }

Practical No – 19

Develop an android application using Kotlin having a Button “Click” and upon clicking
on that Button a Toast message “Button Clicked” should be displayed on screen through
Toast Message

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 59


Mobile Application Development Using Android Subject Code: 4350703

android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/buttonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click" />
</LinearLayout>

MainActivity.kt

package com.example.yourappname // Replace with your actual package name

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)

// Find the button by its ID


val buttonClick = findViewById<Button>(R.id.buttonClick)

// Set click listener on the button


buttonClick.setOnClickListener {
// Display a toast message when the button is clicked
showToastMessage("Button Clicked")
}
}

// Function to show a toast message

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 60


Mobile Application Development Using Android Subject Code: 4350703

private fun showToastMessage(message: String) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}

Practical No – 20

Publish an Android Application on Play Store

Publishing an Android application on the Google Play Store involves several steps. Here's a
step-by-step guide to help you through the process:

1. Prepare your App:


• Ensure that your Android app is fully developed, tested, and ready for public use. 
Optimize the app for different screen sizes and orientations.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 61


Mobile Application Development Using Android Subject Code: 4350703

2. Create a Developer Account:


• Go to the Google Play Developer Console (https://play.google.com/apps/publish)
and sign in with your Google account.
• Pay the one-time registration fee (at the time of writing this, it was $25) to create
your developer account.

3. Prepare Store Listing:


• Provide essential details about your app, such as the app's title, description,
screenshots, promotional graphics, and a high-resolution app icon.
• Write an informative and compelling description for your app to attract potential
users.
• Choose appropriate categories and tags to help users discover your app.

4. Set Pricing & Distribution:


• Decide whether you want to offer your app for free or set a price.
• Select the countries where you want your app to be available.
• Decide if you want to limit the availability to specific devices or if the app is
compatible with all Android devices.

5. Upload APK (Android Package) or App Bundle:


• Build a signed APK or an Android App Bundle that's ready for distribution.
• In the Developer Console, navigate to the "App releases" section and follow the
steps to upload your APK or App Bundle.

6. App Content Rating:


• Complete the content rating questionnaire to classify your app's content and set an
appropriate age rating.

7. Opt-in to App Signing:


• Google Play now encourages developers to use App Signing. If you opt-in, Google
will manage the signing key for you.
• Upload your signing key or create a new one using Google's App Signing service.

8. Review & Publish:

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 62


Mobile Application Development Using Android Subject Code: 4350703

• Once you've completed all the necessary steps and uploaded your APK or App
Bundle, submit your app for review.
• Google Play will review your app to ensure it meets their policies and guidelines.
• This review process may take a few hours to several days, depending on various
factors.

9. Launch Your App:


• Once your app is approved, you can choose to launch it immediately or schedule a
specific date for the release.
• The app will be available to users on the Google Play Store after it's published.

10.Monitor & Update:


• Keep an eye on user feedback and analytics to understand your app's performance.
• Regularly update your app to fix bugs, add new features, and improve user
experience.

Prepared By: VPMP Polytechnic, Department of Computer Engineering Page 63

You might also like