0% found this document useful (0 votes)
2 views75 pages

Mobile Programming Lab Report

The document is a lab report on Mobile Programming submitted by Umanga Basnet at Divya Gyan College, covering various aspects of mobile devices and Android programming. It includes chapters on mobile device features, categories, history, mobile programming lifecycle, popular programming languages, and Android platform setup. The report also discusses user interface design and layout types in Android development.

Uploaded by

umanga basnet
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)
2 views75 pages

Mobile Programming Lab Report

The document is a lab report on Mobile Programming submitted by Umanga Basnet at Divya Gyan College, covering various aspects of mobile devices and Android programming. It includes chapters on mobile device features, categories, history, mobile programming lifecycle, popular programming languages, and Android platform setup. The report also discusses user interface design and layout types in Android development.

Uploaded by

umanga basnet
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/ 75

tDivya Gyan College

(Tribhuvan University)
Kamaladi Mod, Kathmandu

Lab Report of Mobile Programming (CACS 351)


Faculty of Humanities and Social Sciences
Tribhuvan University
Kirtipur, Nepal

Submitted By
Name: Umanga Basnet
Roll No: 75102144

Submitted To
Divya Gyan College
Department of Bachelor of Computer Application
Kamaladi Mod, Kathmandu, Nepal.
Table of Contents

Chapter 1: Introduction to Mobile & Mobile Programming...................................................


Chapter 2: Introduction to Android Programming..................................................................
Chapter 3: Designing the User Interface...............................................................................13
Chapter 4: Android Activity..................................................................................................24
Chapter 5: UI Fragments, Menus and Dialogs......................................................................39
Chapter 6: ListView, GridView and RecyclerView...............................................................47
Chapter 7: Advanced Android Concepts...............................................................................57
Chapter 1: Introduction to Mobile & Mobile Programming

1) What do you mean by mobile device? Explain its features.


A mobile device is a portable handheld electronic device that allows users to perform
activities such as internet surfing, communication, multimedia consumption, and many
other productive tasks.
Features of mobile device:
i) Portability:
Mobile devices are small and lightweight, allowing users to carry them easily in pockets,
bags, or hands.
ii) Wireless connectivity:
They support wireless communication technologies such as Wi-Fi, Bluetooth, and cellular
networks for internet access, calls, and data transfer.
iii) Touchscreen interface:
Most modern mobile devices feature touchscreens, enabling intuitive interaction through
taps and swipes.
iv) Apps and software:
Mobile devices can download and run applications for various purposes, including social
media, gaming, etc.
v) Sensors:
Mobile devices are equipped with sensors like GPS (Global Positioning System),
fingerprint scanners for enhanced functionality.

2) Explain different categories of mobile devices.


Different categories of mobile devices:
i) Smartphones:
The most common and versatile mobile devices combining communication, computing,
imaging ability, texting, and internet browsing. It has high-resolution touchscreens. They
have access to app stores.
E.g. iPhone, Samsung Galaxy, etc.
ii) Tablets:
Tablets are larger than smartphones but smaller than laptops, designed for media
consumption, productivity, and portability. They have larger touchscreens. They support
for apps, games, and multimedia. They are often used for reading, watching videos, and

1
light work tasks.
E.g. iPad, Samsung Galaxy Tab, etc.
iii) E-Readers:
E-Readers are specialized devices designed primarily for reading digital books. E-ink
displays that mimic paper and reduce eye strain. They have long battery life. They are
lightweight and portable.
E.g. Amazon Kindle, Kobo, etc.
iv) Wearable devices:
They are compact devices, worn on the body, often used for fitness tracking, notifications,
and health monitoring. Smartwatches with touchscreens and app support. Fitness trackers
for monitoring steps, heart rate, and sleep.
E.g. Apple Watch, Fitbit, etc.
v) Portable Gaming Consoles:
They are handheld devices designed specially for gaming. They have dedicated gaming
controls with high-quality display for immersive gameplay.
E.g. PSP, PlayStation Portal, Steam Deck, etc.

3) Explain about history of mobile devices in detail.


The history of mobile devices:
i) The Brick Era (1973 - 1988):
It was the first era.
The Brick Era marked the beginning of mobile phone technology, characterized by large,
heavy, and expensive devices. One of the most iconic phones of this era was the Motorola
DynaTac 8000X, introduced in 1983 as the first commercially available handheld cellular
mobile phone. These early phones required enormous batteries to generate the power
needed to reach the nearest cellular network, resulting in bulky and heavy designs. These
phones were primarily used by professionals who required constant communication.
ii) Candy Bar Era (1988 - 1998):
The Candy Bar Era marked one of the most significant leaps in mobile technology.
During this period, network operators recognized the immense value and profitability of
cellular networks, leading to rapid expansion. A key milestone was the introduction of
second generation (2G) technology in Finland, which enabled more efficient and reliable
mobile communication. As cellular network usage increased, the density of cellular sites
grew, reducing the power demands on devices. It allowed phones to become smaller,
lighter, and truly portable.
iii) Feature Phone Era (1998 - 2002):
The Feature Phone Era marked a significant evolution in mobile technology, expanding
beyond basic voice calls, text messaging, and simple games. During this period, mobile

2
phones began incorporating new features such as music, camera, SMS, and internet
access. It also improved connectivity and data transfer capabilities.
iv) The Smartphone Era (2002–present):
The Smartphone Era represents the most transformative period in mobile technology.
Mobile smartphones redefined the core functionality of mobile devices, such as making
calls, sending SMS, taking pictures, and accessing the mobile web. These devices
featured larger screens and Wi-Fi, making them more versatile.

4) What do you mean by mobile programming? Explain life cycle of mobile


application development.
Mobile programming is a set of processes and procedures involved in writing software
for small wireless computing devices.

Life cycle of mobile application development:


There are two interlinked core components of mobile application, i.e.,
i) Mobile application "Front-End" that resides on the mobile device
ii) The service "Back-End" that supports the mobile front-end.

The mobile front-end is the visual and interactive part of the application. The user
experience (UX) usually resides on the device or the thin client and is an icon
representing the app that is visible on the home screen. The application can be
downloaded from the platform app store, side-loaded directly onto the device.
Regardless of what front-end platform is being used, delivering high-quality mobile
applications that delight the end users requires reliable back-ends.
Because of the importance of back-end services for success of mobile applications,
developers have many important decisions that they must consider. These decisions

3
include which services should they build themselves and which third-party services
should they use.

6) List and explain any 5 popular programming languages used for developing
mobile applications.
→ 5 popular programming languages used for developing mobile applications are:
i) Java:
Java is one of the oldest and most popular language[s] for Android app development. It is
an object-oriented programming language that runs on the Java Virtual Machine (JVM)
and is platform independent. It has strong community support with rich libraries and
framework like Android SDK. It is secure and scalable. It is used for native Android
applications.
ii) Kotlin:
Kotlin is an official programming language for Android development introduced by
Google in 2017. It is designed to be more concise and safer than Java. It reduces
boilerplate code making development faster. Null safety feature prevents common errors.
It is used for native Android app development and modern native apps with improved
performance.
iii) Swift:
Swift is a powerful and intuitive programming language developed by Apple for iOS,
macOS, etc. It has high performance and is optimized for Apple devices. It is easy to read
and write compared to Objective-C. It has memory management and platform safety. It is
safe and reliable
reducing app crashes. Used for native ios application.
iv) Dart:
Dart is a modern programming language developed by Google primarily used for building
mobile apps with the Flutter framework. It supports cross-platform development. It offers
fast execution with just-in-time and ahead-of-time compilation. Used for cross-platform
mobile applications using flutter.
v) Javascript:
Javascript is widely used in framework like React Native, Apache Cordova, and Ionic for
building
cross-platform mobile applications. It can be used for both front-end and back-end. It
works with frameworks like React Native for near-native performance. It allows code
reuse across multiple platforms. Used for hybrid and cross-platform mobile app
development.

7) What are different mobile app development approaches? Explain in detail.

4
There are 4 major development approaches when building mobile applications:
i) Native Mobile Applications
ii) Cross-platform Native Mobile Applications
iii) Hybrid-web Applications
iv) Progressive Web Applications

Chapter 2: Introduction to Android Programming


1. What is android platform? Explain about history of android platform
in detail.
Android is a mobile operating system currently developed by Google, based on the Linux
kernel and designed primarily for touchscreen mobile devices such as smartphones and
tablets. And as we said before, Android offers a unified approach to application
development for mobile devices.
History of Android
The history and versions of android are interesting to know. The code names of android
ranges from A to P currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo,
Gingerbread, Honeycomb, Ice Cream Sandwich, Jelly Bean, KitKat, Lollipop,
Marhmallow, Nougat, Oreo and Pie. Let's understand the android history in a sequence.
• Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United
States in October, 2003.
• In 17th August 2005, Google acquired android Incorporation. Since then, it is in the
subsidiary of Google Incorporation.
• The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris
White and Nick Sears.
• Originally intended for camera but shifted to smart phones later because of low market
for camera only.
• Android is the nick name of Andy Rubin given by co-workers because of his love to
robots.
• In 2007, Google announces the development of android OS.
• In 2008, HTC launched the first android mobile.

2. List and explain different versions of android in detail.


Android versions are released with version numbers and dessert-themed names in
alphabetical order . Each version brought new features, performance improvements, and
UI enhancements.

5
Version Name Release Year Key Features

1.5 Cupcake 2009 On-screen keyboard

1.6 Donut 2009 Support for different screen sizes

2.0-2.1 Eclair 2009 Bluetooth 2.1, Google Maps Navigation

2.2 Froyo 2010 USB tethering, Wi-Fi hotspot

2.3 Gingerbread 2010 Enhanced UI, NFC support

3.x Honeycomb 2011 Tablet support

4.0 Ice Cream Sandwich 2011 Unified phone and tablet UI

4.1-4.3 Jelly Bean 2012 Project Butter, Google Now

4.4 KitKat 2013 Improved performance, OK Google

5.0-5.1 Lollipop 2014 Material Design

6.0 Marshmallow 2015 App permissions, Doze mode

7.0-7.1 Nougat 2016 Multi-window, better notifications

8.0-8.1 Oreo 2017 Picture-in-picture, notification dots

9.0 Pie 2018 Adaptive battery, gesture navigation

10 - 2019 Privacy controls, dark mode

11 - 2020 Conversation notifications

12 - 2021 Material You, privacy dashboard

13 - 2022 Themed icons, improved permissions

3. How we can setup environment for android? Explain.


Environment Setup
In order to write an Android application, we are going to need a development
environment. Google has made a very useful tool for all Android Developers, the
Android Studio. Android Studio is the official IDE for Android development, and with a
single download includes everything you need to begin developing Android apps.
Included in the download kit, are the Software Development Kit (SDK), with all the
Android libraries we may need, and the infrastructure to download the many Android

6
emulator instances, so that we can initially run our application, without needing a real
device. So, we are going to download and install Android Studio.

Step 1 - First, we have to have installed the Java Development Kit (JDK) from Oracle. If
you do not, please you should download the latest JDK from the https://www.oracle.com/.
After downloading JDK, please install it in your system.
Step 2 – After installing JDK, now it’s the time for you to setup environment variables.
For this procedure, right click This PC (My Computer) -> Properties -> Advanced System
Settings -> Environment Variables -> New. Now setup new environment variable as
follows:
Figure 2-1. Setting up environment variable

Here, variable value must be the path where JDK is installed. Now click OK.
Step 3 – Now download the latest android studio and install in your system. After
installation following window appears in your computer screen.
Figure 2-2. First look of android studio after installation

7
Congratulations! Android Studio has been successfully installed in your computer system.

4. What do you mean by view hierarchy? Explain with the help of


suitable Example
The View Hierarchy
Your widgets exist in a hierarchy of View objects called the view hierarchy. To
demonstrate view hierarchy now I am going to create another layout file named as
“second.xml” which contains the following widgets:
• a vertical LinearLayout
• a TextView
• a horizontal LinearLayout
• two Buttons
Figure 2-9. Arrangement of widgets to demonstrate view hierarchy

8
second.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text_question"
android:textStyle="bold"
android:textSize="20sp"/>
<LinearLayout

9
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text_true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text_false"/>

</LinearLayout>
</LinearLayout>

Figure 2-10. Hierarchical layout of widgets and attributes

The root element of this layout’s view hierarchy is a LinearLayout. As the root element,
the LinearLayout must specify the Android resource XML namespace at
http://schemas.android.com/ apk/res/android.
LinearLayout inherits from a subclass of View named ViewGroup. A ViewGroup is a
widget that contains and arranges other widgets. You use a LinearLayout when you want
widgets arranged in a single column or row. Other ViewGroup subclasses are
FrameLayout, TableLayout, and RelativeLayout.
When a widget is contained by a ViewGroup, that widget is said to be a child of the
ViewGroup. The root LinearLayout has two children: a TextView and another
LinearLayout. The child LinearLayout has two Button children of its own.
.

10
6. How can we create string resources? Explain with the help of suitable
example.
Creating String Resources
Since string resources, we are referencing in second.xml do not exist yet. Now, we need
to fix that by adding strings to string.xml file. Every project includes a default strings file
named strings.xml. In the package explorer, find the res/values directory, reveal its
contents, and open strings.xml.
Now add following lines of code in strings.xml file.

<resources>
<string name="app_name">My Application</string>
<string name="text_question">Android Studio is better than Eclipse</string>
<string name="text_true">True</string>
<string name="text_false">False</string>
</resources>

7. Write a set of codes for creating activity. Also link xml file
“activity_main.xml” to this activity.

11
Step 1: Create Java Activity File
package com.example.practice;

import android.app.Activity;
import android.os.Bundle;

public class mainActivity extends Activity {


@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
}

}
Step 2: Create the XML Layout File
🔹 res/layout/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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/helloText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, BCA!"
android:textSize="24sp"
android:textColor="#000000" />
</LinearLayout>

12
13
Chapter 3: Designing the User Interface
1. What do you mean by layout? List and explain different types of layout used in
android with their major attributes.
A layout defines the structure for a user interface in your app, such as in an
activity. All elements in the layout are built using a hierarchy of View and View
Group objects. Layouts can be defined in XML files or created programmatically
in Java/Kotlin.
Types of layouts are:
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Absolute Layout
5. Constraint Layout

1. Linear Layout:
Linear Layout is a view group that aligns all children in a single
direction, vertically or horizontally. You can specify the layout
direction with the android: orientation attribute.

Major Attributes of Linear Layout:

android:baselineAligned When set to false, prevents the layout from aligning


its children's baselines.

android:orientation Should the layout be a column or a row? Use


"horizontal" for a row, "vertical" for a column.

android:divider Draw able to use as a vertical divider between buttons.

android:gravity Specifies how an object should position its content,


on both the X and Y axes, within its own bounds.

2. Relative Layout:
Relative Layout Positions child views relative to each other or to the parent
layout. It is a very powerful utility for designing a user interface because it can
14
eliminate nested view groups and keep your layout hierarchy flat, which
improves performance.

Major Attributes of Relative Layout:

android:layout_above Positions the bottom edge of this


view above the given anchor view
ID.

android:layout_alignBaseline Positions the baseline of this


view on the baseline of the given
anchor view ID.

android:layout_alignBottom Makes the bottom edge of this view


match the bottom edge of the given
anchor view ID.

android:layout_alignEnd Makes the end edge of this view match


the end edge of the given anchor view
ID.

android:layout_alignLeft Makes the left edge of this view match


the left edge of the given anchor view
ID.

android:layout_alignParentBotto If true, makes the bottom edge of


m this view match the bottom edge of
the parent.

3. Table Layout:
Table Layout is a layout that arranges its children into rows and columns. It
consists of a number of Table Row objects, each defining a row (actually, you
can have other children, which will be explained below).

15
Major Attributes of Table Layout:

android:collapseColum The zero-based index of the columns to collapse. The


ns column indices must be separated by a comma: 1, 2, 5.
Illegal and duplicate indices are ignored.

android:shrinkColum The zero-based index of the columns to shrink. The column


ns indices must be separated by a comma: 1, 2, 5. Illegal and
duplicate indices are ignored.

android:stretchColum The zero-based index of the columns to stretch. The column


ns indices must be separated by a comma: 1, 2, 5. Illegal and
duplicate indices are ignored.

4. Absolute Layout:
An Absolute Layout lets you specify exact locations (x/y
coordinates) of its children. Absolute layouts are less flexible
and harder to maintain than other types of layouts without
absolute positioning.
Major Attributes of Absolute Layout:

android:layout_x This specifies the x-coordinate of the view.

android:layout_y This specifies the y-coordinate of the view.

5. Constraint Layout:
Constraint layout is an advanced version of a Relative layout. It
is used to reduce the child view hierarchies and improve the
performance. A Constraint Layout is similar to a Relative Layout,
but with more power. The aim of this layout is to improve the
performance of the applications by removing the nested views
with a flat and flexible design.

Major Attributes of Constraint Layout:

layout_constraintTop_toTopOf Align the top of the


desired view to the top of
another.

16
layout_constraintTop_toBotto Align the top of the
mOf desired view to the
bottom of another.

layout_constraintBottom_toTo Align the bottom of the


pOf desired view to the top of
another.

layout_constraintBottom_toBo Align the bottom of the


ttomOf desired view to the
bottom of another.

layout_constraintLeft_toLeftO Align the left of the


f desired view to the left of
another.

layout_constraintLeft_toRight Align the left of the


Of desired view to the left of
another.

2. Differentiate Linear Layout and Relative Layout with example.

Linear Layout Relative layout

Arranges views in a single direction Arranges views relative to each other or to


(horizontal or vertical). the parent.
Requires android: orientation No orientation
(vertical/horizontal). needed.

Fixed sequence: top to bottom or left to More flexible: views can be placed
right. anywhere using relative rules.
More efficient for simple layouts. Slightly less efficient than Linear Layout.

May require nested layouts to achieve Requires less nesting due to relative rules.
positioning.

17
Example Of Linear Layout:

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is label 1"
android:textSize="20sp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is label 2"
android:textSize="20sp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is label 3"
android:textSize="20sp"/>

</LinearLayout>

18
Figure 2.1: Output produced for Linear Layout

Example of Relative 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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 1"
android:textSize="20sp"
android:id="@+id/label1" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 2"
android:textSize="20sp"
android:id="@+id/label2"
android:layout_toRightOf="@+id/label1"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 3"
android:textSize="20sp"
android:id="@+id/label3"
android:layout_below="@+id/label1" />

</RelativeLayout>

19
Figure 2.2: Output demonstrating RelativeLayout
3. Explain any five widgets with their attributes in detail.
Widgets are the building blocks you use to compose a user interface. A widget can
show text or graphics, interact with the user, or arrange other widgets on the screen.

1. TextView
It is a user interface element that displays text to the user. Following
are the attributes associated with Text View.

Major Attributes:
 android:text – Sets the text content.

 android:textSize – Sets the size of the text (e.g., 16sp).

 android:textColor – Sets the color of the text.

 android:gravity – Aligns text within the TextView (e.g., center, right).

 android:maxLines – Limits the number of text lines.

2. EditText
A user interface element for entering and modifying text. When you
define an edit text widget, you must specify the input Type attribute.
For example, for plain text input set input Type to "text".

Major Attributes:

 android:hint – Placeholder text shown when empty.


 android:inputType – Type of input (e.g., text, number, email, password).
 android:maxLength – Limits character input.
 android:textColorHint – Color of the hint text.
 android:lines – Sets the number of visible lines.

3. Button
It is a user interface element the user can tap or click to perform an
action. Following are the attributes associated with Button.

Major Attributes:

 android:text – Text displayed on the button.

 android:onClick – Name of the method to call when clicked.

20
 android:background – Background color or drawable.

 android:textColor – Text color of the button.

4. Checkbox
A checkbox is a specific type of two-state button that can be either
checked or unchecked. Following are the attributes associated with
Checkbox.

Major Attributes:

 android:text – Label for the checkbox.

 android:checked – Initial checked state (true or false).

 android:buttonTint – Color of the checkbox.

 android:onCheckedChanged – Listener when state changes.

5. ImageView
Used to display images from drawable resources or URLs.

Major Attributes:

 android:src – Image source (e.g., @drawable/image_name).

 android:scaleType – How the image should be resized (fit Center, center Crop)

 android:adjustViewBounds – Maintains aspect ratio if set to true.

 android:contentDescription – Description for accessibility.

4. What do you mean by event? Explain event handling in detail.


An event is an action or occurrence that the system or user triggers, which the app
can respond to.

Event handling refers to the process of capturing an event (like a user tap) and then
responding to it using listeners or handlers .It allows developers to define what the
app should do when an event occurs — such as displaying a message, navigating to
another screen, or updating UI elements.

21
Event Handler Event Listener & Description

onClick() OnClickListener()
This is called when the user either clicks or touches or
focuses upon any widget like button, text, image etc.

onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or
focuses upon any widget like button, text, image etc. for
one or more seconds.

onFocusChange() OnFocusChangeListener()
This is called when the widget loses its focus i.e. user goes
away from the view item

onKey() OnFocusChangeListener()
This is called when the user is focused on the item and
presses or releases a hardware key on the device.

5. Design a simple UI for patient registration in hospital.


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

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Patient Registration"
android:textSize="24sp"
android:textStyle="bold"
android:layout_gravity="center"
android:paddingBottom="20dp" />

<!-- Patient Name -->


<EditText
android:id="@+id/etName"

22
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full Name"
android:inputType="textPersonName" />

<!-- Age -->


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

<!-- Gender -->


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

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

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

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

<!-- Contact Number -->


<EditText
android:id="@+id/etContact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Contact Number"
android:inputType="phone" />

<!-- Symptoms -->


<EditText

23
android:id="@+id/etSymptoms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Symptoms"
android:inputType="textMultiLine"
android:minLines="3"
android:gravity="top" />

<!-- Register Button -->


<Button
android:id="@+id/btnRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:layout_marginTop="20dp" />

</LinearLayout>
</ScrollView>

Output:

24
Chapter 4: Android Activity

1. What do you mean by android activity? Explain android activity life cycle in detail.
An Android activity represents a single screen with a user interface in an Android
application. It's like a window or a page where the user can interact with the app.
For example, an email app might have one activity to show a list of new emails,
another to compose an email, and another to read emails

Activities serve as the entry point for a user's interaction with an app and manage
the UI components and user input. Every Android app may have one or more
activities.

Android Activity Life Cycle:

The life cycle of an activity refers to the set of states the activity goes through
from creation to destruction. It includes several callback methods that allow
developers to handle transitions between states effectively.

Here are the main lifecycle methods in detail:

1. onCreate()
o Called when the activity is first created.
o Used to initialize components like layout, data binding, etc.
o This is where you set up the user interface (using setContentView()).
2. onStart()
o Called just before the activity becomes visible to the user.
o At this point, the activity is visible but not interactive.
3. onResume()
o Called when the activity starts interacting with the user.
o It is the state where the activity is at the top of the activity stack and
the user can interact with it.

25
4. onPause()
o Called when the system is about to start resuming another activity.
o It is used to pause ongoing actions like animations, music, or save
unsaved changes.
5. onStop()
o Called when the activity is no longer visible to the user.
o Use this method to release heavy resources or perform cleanup.
6. onRestart()
o Called after the activity has been stopped, just before it is started
again.
o Useful to re-initialize resources released in onStop().
7. onDestroy()
o Called before the activity is destroyed.
o This is the final call before the activity is terminated, either by the
user or the system.

2. How can you declare multiple activities in manifest? Explain.


In Android, when you create multiple activities in your application, each activity
must be declared in the AndroidManifest.xml file. This declaration is
necessary so that the Android system knows about all the components of your
application.

We declare multiple activity by using the following code:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raazu.myapplication">

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

26
<activity android:name=".FirstActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

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

</application>
</manifest>

3. What do you mean by intent? Explain.

An Intent in Android is a messaging object you use to request an action from


another app component (such as an Activity, Service, or BroadcastReceiver).
Intents serve two primary purposes:

1. Component-to-component communication: You can start another activity or


service within your app (or in another app) by passing an Intent to the
system.
2. Broadcasting: You can send a system-wide event that any interested app can
receive.

Under the hood, an Intent carries either:

 An explicit target (the exact class of the component to start), or


 An implicit action (a general action string, like “VIEW” or “SEND”), which
the system matches against other apps’ intent-filters.

In the context of activities, intents are typically used to start a new activity.
For this, the Intent class is used like this:
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
This creates an intent to launch SecondActivity from FirstActivity.

4. How can you pass data between multiple activities using intent? Explain.

27
To pass data between activities using intents, Android provides the putExtra()
method. This method allows you to attach key-value pairs (called extras) to the
intent.

The receiving activity can then use getIntent() to access the intent and extract the
data using corresponding getExtra methods.

We can pass the intent data by following way:

 Send the activity:


Intent i = new Intent(FirstActivity.this, SecondActivity.class);

// Passing data using putExtra


i.putExtra("id", 001);
i.putExtra("name", "Ram");
i.putExtra("address", "KTM");

startActivity(i);

 Receive the activity:


Intent i = getIntent();
int id = i.getIntExtra("id", 0); // default value 0
String name = i.getStringExtra("name");
String address = i.getStringExtra("address");

// Displaying the received data


TextView txt = findViewById(R.id.text2);
txt.setText("Id=" + id + "\n" + "Name=" + name + "\n" + "Address=" +
address);

With these two steps—calling putExtra(...) before startActivity(...) and


then using get…Extra(...) in the destination—you can pass any serializable
data between your activities in Android.

5. Develop an android application which get result back from a child activity.

FirstActivity.java:
public class FirstActivity extends Activity {
TextView txt;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {

28
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);

txt = findViewById(R.id.text1);
btn = findViewById(R.id.button1);

btn.setOnClickListener(view -> {
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(i, 2); // Request code = 2
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 2) {
String message = data.getStringExtra("message");
txt.setText(message);
}
}
}

SecondActivity.java
public class SecondActivity extends Activity {
Button btn;

@Override
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.second_activity);

29
btn = findViewById(R.id.button2);

btn.setOnClickListener(view -> {
Intent i = new Intent();
i.putExtra("message", "Hello First Activity!");
setResult(2, i);
finish();
});
}
}

First_activity.xml
<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">

<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is First Activity"
android:textSize="20sp"
android:layout_gravity="center" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second"

30
android:layout_gravity="center" />
</LinearLayout>

Second_activity.xml
<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">

<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:textSize="20sp"
android:layout_gravity="center" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to First"
android:layout_gravity="center" />
</LinearLayout>

6. Develop an android application to calculate simple interest. Your application should


contain fields to input principal, rate, time and button for event handling.
Calculate and display result in a TextView.

SimpleInterestActivity.java
public class SimpleInterestActivity extends Activity {
EditText edtP, edtR, edtT;
31
Button btnCalculate;
TextView txtResult;

@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_simple_interest);

edtP = findViewById(R.id.edtP);
edtR = findViewById(R.id.edtR);
edtT = findViewById(R.id.edtT);
btnCalculate = findViewById(R.id.btnCalculate);
txtResult = findViewById(R.id.txtResult);

btnCalculate.setOnClickListener(v -> {
float p = Float.parseFloat(edtP.getText().toString());
float r = Float.parseFloat(edtR.getText().toString());
float t = Float.parseFloat(edtT.getText().toString());
float si = (p * r * t) / 100;
txtResult.setText("Simple Interest = " + si);
});
}
}

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

32
<EditText android:id="@+id/edtP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Principal" />

<EditText android:id="@+id/edtR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Rate" />

<EditText android:id="@+id/edtT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Time" />

<Button android:id="@+id/btnCalculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate" />

<TextView android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result appears here" />
</LinearLayout>
7. Design a signup form using any layout of your choice.
 Your design must include important widgets like TextView,
EditText, Button, RadioButton, CheckBox, Spinner etc.
 When user clicks a Button display inputted data in a TextView.

SignupActivity.java
package com.example.myapp;

33
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class SignupActivity extends Activity {


EditText edtName, edtEmail;
RadioGroup genderGroup;
RadioButton radMale, radFemale;
CheckBox chkReading, chkTraveling;
Spinner spCountry;
Button btnSubmit;
TextView txtResult;

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

edtName = findViewById(R.id.edtName);
edtEmail = findViewById(R.id.edtEmail);
genderGroup = findViewById(R.id.genderGroup);
radMale = findViewById(R.id.radMale);
radFemale = findViewById(R.id.radFemale);
chkReading = findViewById(R.id.chkReading);
chkTraveling = findViewById(R.id.chkTraveling);
spCountry = findViewById(R.id.spCountry);
btnSubmit = findViewById(R.id.btnSubmit);
txtResult = findViewById(R.id.txtResult);

btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override

34
public void onClick(View v) {
String name = edtName.getText().toString();
String email = edtEmail.getText().toString();

String gender = "";


if (radMale.isChecked()) gender = "Male";
else if (radFemale.isChecked()) gender = "Female";

String hobbies = "";


if (chkReading.isChecked()) hobbies += "Reading ";
if (chkTraveling.isChecked()) hobbies += "Traveling ";

String country = spCountry.getSelectedItem().toString();

String output = "Name: " + name +


"\nEmail: " + email +
"\nGender: " + gender +
"\nHobbies: " + hobbies +
"\nCountry: " + country;

txtResult.setText(output);
}
});
}
}

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

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

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Signup Form"
android:textSize="24sp"
android:textStyle="bold"
android:gravity="center" />

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

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender:" />

36
<RadioGroup
android:id="@+id/genderGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hobbies:" />

<CheckBox
android:id="@+id/chkReading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reading" />

<CheckBox
android:id="@+id/chkTraveling"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

37
android:text="Traveling" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Country:" />

<Spinner
android:id="@+id/spCountry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/countries" />

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

<TextView
android:id="@+id/txtResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result will be shown here"
android:paddingTop="16dp"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>

Strings.xml

<resources>

38
<string name="app_name">SignupApp</string>
<string-array name="countries">
<item>Nepal</item>
<item>India</item>
<item>USA</item>
<item>UK</item>
<item>Japan</item>
</string-array>
</resources>

39
Chapter 5: UI Fragments, Menus and Dialogs

1. What do you mean by fragment? Explain lifecycle of fragment in detail.


A fragment is a modular component within an Android activity, often
referred to as a "sub-activity." An activity can host multiple fragments,
allowing for the display of more than one screen's worth of information
within a single activity. Fragments are designed to represent a specific
behavior or a portion of the user interface (UI) inside an
FragmentActivity. This design enables developers to create more
dynamic and flexible UI layouts.

A fragment's lifecycle is tightly bound to the lifecycle of its host activity. When
the activity is paused, all its fragments are also paused; when the activity is
destroyed, so are its fragments. However, while the activity is running, fragments
can be manipulated independently. The FragmentManager handles a back stack
of fragment transactions, allowing users to navigate backward through fragment
changes using the Back button.

Here's a breakdown of the fragment lifecycle methods:

 onAttach(Activity): This method is called only once, when the


fragment is first attached to an activity.
 onCreate(Bundle): This is where the fragment initializes its state.
 onCreateView(LayoutInflater, ViewGroup, Bundle): This method is
responsible for inflating the layout for the fragment's UI.
 onActivityCreated(Bundle): Called after the host activity's
onCreate() method has completed.
 onViewStateRestored(Bundle): This provides the fragment with the
information that the saved state of its view hierarchy has been
restored.
 onStart(): This makes the fragment visible to the user.
 onResume(): The fragment becomes interactive at this point.

40
 onPause(): This is called when the fragment is no longer
interactive, typically when another activity comes into the
foreground.
 onStop(): The fragment is no longer visible to the user.
 onDestroyView(): This allows the fragment to clean up any
resources associated with its view.
 onDestroy(): The fragment performs its final cleanup.
 onDetach(): Called immediately before the fragment is no longer
associated with its activity.

2. How can you create UI fragment? Explain with example.

To create a UI fragment, you need to follow the following steps:


 First, create the fragment layout (res/layout/fragment_profile.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="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="@+id/profile_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_profile" />
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="John Doe" />
<Button
android:id="@+id/edit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit Profile" />
</LinearLayout>

41
Create the Fragment class (ProfileFragment.java)
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.fragment.app.Fragment;

public class ProfileFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);

// Initialize UI components
Button editButton = view.findViewById(R.id.edit_button);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),
"Edit Profile Clicked!",
Toast.LENGTH_SHORT).show();
}
});

42
return view;
}
}
Add the Fragment to an Activity
<!-- res/layout/activity_main.xml -->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
android:name="com.yourpackage.ProfileFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>

3. Develop an android application to display multiple fragments in activity


using fragment manager.

a) 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"
tools:context=".MainActivity">

43
<FrameLayout
android:id="@+id/fragment_container_one"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#FFCDD2" /> <FrameLayout
android:id="@+id/fragment_container_two"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#BBDEFB" /> </LinearLayout>

b) fragment_one.xml

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


<FrameLayout
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"
tools:context=".FragmentOne">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="This is Fragment One"
android:textSize="20sp"
android:textColor="@android:color/black"/>

</FrameLayout>

c) fragment_two.xml

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

44
<FrameLayout
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"
tools:context=".FragmentTwo">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="This is Fragment Two"
android:textSize="20sp"
android:textColor="@android:color/black"/>

</FrameLayout>

d) MainActivity.java

package com.example.multiplefragmentsdemo; // Adjust package name

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

45
FragmentManager fragmentManager =
getSupportFragmentManager();

// Check if fragments are already added (e.g., after screen rotation)


if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();

// Add FragmentOne to fragment_container_one


FragmentOne fragmentOne = new FragmentOne();
fragmentTransaction.add(R.id.fragment_container_one,
fragmentOne, "FRAGMENT_ONE_TAG");

// Add FragmentTwo to fragment_container_two


FragmentTwo fragmentTwo = new FragmentTwo();
fragmentTransaction.add(R.id.fragment_container_two,
fragmentTwo, "FRAGMENT_TWO_TAG");

fragmentTransaction.commit();
}
}
}

e) FragmentOne.java

package com.example.multiplefragmentsdemo; // Adjust package name

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment {

46
public FragmentOne() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}

f) FragmentTwo.java

package com.example.multiplefragmentsdemo; // Adjust package name

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentTwo extends Fragment {

public FragmentTwo() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

47
return inflater.inflate(R.layout.fragment_two, container, false);
}
}

48
Chapter 6: ListView, GridView and RecyclerView
1. What do you mean by ListView? Explain its features.

ListView is a user interface component that displays a scrollable list of items in a vertical
manner to present large sets of similar data in an organized and easy-to-browse format.
Some key features of ListView are:
 It displays a vertically-scrollable collection of views, where each view is
positioned immediately below the previous view in the list.

 ListView uses Adapter classes which add the content from a data source
(such as string array, array, database, etc.)

 ListView is a default scrollable which does not use other scroll view.

 ListView is implemented by importing android.widget.ListView class.

2. What do you mean by GridView? Explain its features.

GridView is a type of view used in UI development that displays items in a two-


dimensional, scrollable grid format.
In Android, GridView is a subclass of AbsListView that allows developers to arrange items
in rows and columns. It is used to show data items in a grid, like images in a photo gallery
or products in a shopping app.

Some key features of GridView are:


 GridView displays items in two-dimensional scrolling grid.

 GridView uses Adapter classes which add the content from data source
(such as string array, array, database etc.)

 GridView is a default scrollable which does not use other scroll view.

 GridView is implemented by importing android.widget.GridView class.

49
3. What do you mean by RecyclerView? Explain its features.

RecyclerView is an advanced and flexible Android UI component used to


display a large set of data in a scrollable list or grid. It is an efficient
replacement for older views like ListView and GridView.

The key idea behind RecyclerView is to reuse item views ("recycling") instead
of creating a new view for each data item to improve performance with long
lists.

Some of key features of RecyclerView are:

 RecyclerView widget is a more advanced and flexible version of


ListView. So, we can use RecyclerView to display large dataset.

 RecyclerView contains integrated animations for adding, updating and


removing items.

 RecyclerView enforces the recycling of views by using the


ViewHolder pattern.

 RecyclerView supports both grids and lists.

 RecyclerView supports vertical and horizontal scrolling.

4. Differentiate ListView and GridView with example.


ListView GridView
ListView displays items in a single GridView arranges items in a scrollable
vertical column, such as lists of text or grid with multiple columns, such as
content. images or items in a tile layout.
ListView items stretch across the full GridView items are sized to fit within
width of the screen. the grid structure and often share row
space
It uses adapters like ArrayAdapter or It also uses adapters like ArrayAdapter
BaseAdapter to display the data in the or BaseAdapter, but requires more
UI. attention to spacing and layout because
of its grid structure.
ListView contains built-in dividers, GridView requires manual spacing
such as thin horizontal line between using padding or margins.
items
ListView is now commonly replaced by GridView is often replaced by
RecyclerView with a RecyclerView with a
LinearLayoutManager. GridLayoutManager for better
flexibility and performance.

50
Example of ListView:

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


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

2
android:layout_width="match_parent"
android:layout_height="match_parent">

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

</RelativeLayout>

Example of GridView:

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

<GridView
android:layout_width="match_parent"
android:id="@+id/mygrid"
android:numColumns="3"
android:layout_height="match_parent" />
</RelativeLayout>

5. Differentiate ListView and RecyclerView with example.


ListView RecyclerView
ListView is an older Android component RecyclerView is a more modern and
for displaying only vertical scrolling flexible display vertical, horizontal,
lists. grid, or staggered layouts using
LayoutManager.
51
Using the ViewHolder pattern is optional But in RecyclerView, it is mandatory
in ListView. and built into its architecture for better
performance.
ListView recycles views using RecyclerView uses a optimized
convertView to reuse existing item recycling system handled by the
views instead of creating new ones each adapter and ViewHolder.
time.
ListView uses simpler ArrayAdapter RecyclerView uses ViewHolder
which can lag with heavy lists. pattern to perform better with large or
complex datasets.
ListView has built-in RecyclerView, click listeners must be
setOnItemClickListener() support that implemented manually inside the
helps to detect item clicks with just a few adapter.
lines of code.

Example of ListView:

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


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

2
android:layout_width="match_parent"
android:layout_height="match_parent">

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

</RelativeLayout>

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

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"

52
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

6. Develop an android application to display id, name and address of


5 students using ListView.

student_item.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="wrap_content"
android:orientation="vertical"
android:padding="10dp">

<TextView
android:id="@+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:textStyle="bold" />

<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />

53
<TextView
android:id="@+id/tvAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address" />

</LinearLayout>

Student.java

public class Student {


private int id;
private String name;
private String address;

public Student(int id, String name, String address) {


this.id = id;
this.name = name;
this.address = address;
}

public int getId() {


return id;
}

public String getName() {


return name;
}

54
public String getAddress() {
return address;
}
}

StudentAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class StudentAdapter extends ArrayAdapter<Student> {

public StudentAdapter(Context context, List<Student> students) {


super(context, 0, students);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
Student student = getItem(position);

if (convertView == null) {
convertView = LayoutInflater.from(getContext())

55
.inflate(R.layout.student_item, parent, false);
}

TextView tvId = convertView.findViewById(R.id.tvId);


TextView tvName = convertView.findViewById(R.id.tvName);
TextView tvAddress = convertView.findViewById(R.id.tvAddress);

tvId.setText("ID: " + student.getId());


tvName.setText("Name: " + student.getName());
tvAddress.setText("Address: " + student.getAddress());

return convertView;
}
}

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

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

</RelativeLayout>

56
. MainActivity.java
import android.os.Bundle;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private ListView listViewStudents;

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

listViewStudents = findViewById(R.id.listViewStudents);

// Create 5 students
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(1, "Alice", "123 Main St"));
students.add(new Student(2, "Bob", "456 Oak Ave"));
students.add(new Student(3, "Charlie", "789 Pine Rd"));
students.add(new Student(4, "Diana", "321 Maple Dr"));
students.add(new Student(5, "Ethan", "654 Cedar Ln"));

// Set adapter
StudentAdapter adapter = new StudentAdapter(this, students);

57
listViewStudents.setAdapter(adapter);
}
}

58
Chapter 7: Advanced Android Concepts

1. What do you mean by SQLite? Explain its features.

SQLite is a lightweight, self-contained, serverless relational database management


system (RDBMS). It is embedded directly into the application and stores data in a single
file on disk. Unlike other RDBMS systems like MySQL or PostgreSQL, SQLite does not
require a separate server process to operate.

It is written in C and is widely used in mobile applications (like Android and iOS),
desktop software, and embedded systems due to its simplicity and efficiency.

Features of SQLite:

1. Serverless
o SQLite does not require a separate server to run. It reads and writes
directly to ordinary disk files.
2. Zero Configuration
o No setup or administration required. Applications can use SQLite without
installing or configuring a database server.
3. Cross-Platform
o Works on many operating systems like Windows, Linux, and macOS with
the same database file format.
4. Single Database File
o All data including tables, indexes, and the schema is stored in a single file,
making it easy to move or backup.
5. Lightweight
o Very small in size (~500KB) and uses minimal system resources.2.
Explain advantages and disadvantages of using SQLite.

Advantages and Disadvantages of Using SQLite are as follows:

Advantages of SQLite:

1. Lightweight and Fast


o Requires very little disk space and memory. Ideal for embedded systems
and mobile devices.
2. Serverless Architecture
o No need for a separate server. The database is stored as a simple file,
which simplifies setup and maintenance.
3. Easy to Use
o Minimal configuration required. Developers can start using it right away
without complex installation.
4. Cross-Platform Support
o SQLite databases are portable across different operating systems.
5. Single File Database

59
o Entire database (schema, data, indexes) is stored in a single .sqlite or .db
file, making it easy to move, copy, or backup.

Disadvantages of SQLite:

1. Not Suitable for High-Concurrency Applications


o Limited support for concurrent writes. It uses file-level locking, which
may become a bottleneck in multi-user systems.
2. Lacks Advanced Features
o Does not support user management, stored procedures, or advanced server-
side functions like MySQL/PostgreSQL.
3. Limited Scalability
o Designed for smaller-scale applications. Not ideal for very large databases
or enterprise-level systems.
4. No Built-in Access Control
o It doesn't support roles, permissions, or user management out of the box.
5. File-Based Storage
o Since it's file-based, file corruption can be more damaging, and large file
handling can be slower compared to server-based DBMS.
6. Basic Tooling
o Fewer GUI and management tools available compared to MySQL or
PostgreSQL.

Conclusion:

 SQLite is ideal for: Mobile apps, embedded devices, desktop software, small-to-
medium web apps, testing, and prototyping.
 Not ideal for: Large-scale, multi-user, high-concurrency enterprise applications.

It’s a great choice when simplicity, portability, and zero-configuration are important.

3. How can you establish connection using SQLite in android? Explain with the help
of suitable example.

In Android, SQLite is built-in and accessed using the SQLiteOpenHelper class, which
helps manage database creation and version management.

Steps to Establish a Connection to SQLite in Android:

1. Create a class that extends SQLiteOpenHelper


2. Override onCreate() and onUpgrade() methods
3. Use getWritableDatabase() or getReadableDatabase() to establish the connection

Create a database helper class

public class MyDatabaseHelper extends SQLiteOpenHelper {

60
private static final String DATABASE_NAME = "StudentDB.db";

private static final int DATABASE_VERSION = 1;

// Constructor

public MyDatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

// Called when the database is created for the first time

@Override

public void onCreate(SQLiteDatabase db) {

String query = "CREATE TABLE students (" +

"id INTEGER PRIMARY KEY AUTOINCREMENT, " +

"name TEXT, " +

"age INTEGER)";

db.execSQL(query);

// Called when the database needs to be upgraded

@Override

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

db.execSQL("DROP TABLE IF EXISTS students");

onCreate(db);

61
Using helper class in a activity

public class MainActivity extends AppCompatActivity {

MyDatabaseHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Create or open the database

dbHelper = new MyDatabaseHelper(this);

// Establishing connection

SQLiteDatabase db = dbHelper.getWritableDatabase(); // or getReadableDatabase()

// Insert sample data

ContentValues values = new ContentValues();

values.put("name", "John");

values.put("age", 21);

db.insert("students", null, values);

In Android, SQLite connections are managed using the SQLiteOpenHelper class. This
structure helps manage database versions, and makes it easier to perform CRUD (Create,
Read, Update, Delete) operations efficiently within your app.

62
4. Explain the process of creating Database and Tables using SQLite in android.

In Android, the process of creating a database and tables using SQLite involves
extending the SQLiteOpenHelper class, which handles database creation and version
control.

1. Steps to Create Database and Tables in SQLite (Android):


Step 1: Create a Class Extending SQLiteOpenHelper

This class helps manage the database and its tables.

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Database Name and Version

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

private static final int DATABASE_VERSION = 1;

// Constructor

public MyDatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

// onCreate() is called when the database is created for the first time

@Override

public void onCreate(SQLiteDatabase db) {

// SQL query to create a table

String createTableQuery = "CREATE TABLE students (" +

"id INTEGER PRIMARY KEY AUTOINCREMENT, " +

"name TEXT, " +

"age INTEGER)";

db.execSQL(createTableQuery); // Execute the query

63
}

// onUpgrade() is called when the database version is changed

@Override

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

// Drop the old table if it exists

db.execSQL("DROP TABLE IF EXISTS students");

// Create the new version of the table

onCreate(db);

Step 2: Use the Helper Class to Create the Database

You can now create an instance of the database helper class in your activity or fragment.

public class MainActivity extends AppCompatActivity {

MyDatabaseHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// This line creates or opens the database and calls onCreate() if it doesn't exist

dbHelper = new MyDatabaseHelper(this);

64
// This establishes the connection to the database

SQLiteDatabase db = dbHelper.getWritableDatabase();

A database named StudentDB.db is created in the app's internal storage. Table named
students with fields id, name, and age is created within that database.

5. What do you mean by API? Explain its types.

API stands for Application Programming Interface. It is a set of rules and protocols
that allow different software applications to communicate with each other.

In simple terms, an API acts like a messenger that takes a request from one application,
sends it to another, and then brings back the response.

Example:

When you use a weather app, it calls an API to get weather data from a server. You don’t
see the process – you just see the result.

Types of APIs:

There are several types of APIs based on usage, access level, and technology:

1. Web APIs (Also called Web Services)

 These are APIs that allow communication over the web using HTTP.
 Example: REST API, SOAP API, GraphQL API

REST API (Representational State Transfer)

 Most common.
 Uses HTTP methods like GET, POST, PUT, DELETE.
 Returns data in JSON or XML format.
 Simple and fast.

b. SOAP API (Simple Object Access Protocol)

 XML-based.
 More strict and secure than REST.
 Often used in enterprise-level applications.

c. GraphQL API

 Developed by Facebook.

65
 Allows clients to request exactly the data they need.
 More flexible than REST.

2. Open APIs (Public APIs)

 Available to all developers.


 Anyone can use them, often with an API key.
 Example: Google Maps API, Weather API

3. Internal APIs (Private APIs)

 Used within a company.


 Not exposed to outside users.
 Help different teams or systems within the organization communicate.

4. Partner APIs

 Shared with specific business partners.


 More controlled than public APIs.
 Often used for B2B integrations.

5. Library APIs / Local APIs

 Provided by software libraries or operating systems.


 Allow access to functions like file handling, graphics, etc.
 Example: Java API, Windows API

Conclusion:

An API is a crucial tool for enabling communication between software systems.


Depending on the use case, developers choose from different types of APIs like REST,
SOAP, or GraphQL, and whether it is public, private, or partner-based.

66
6. How Do You Communicate Your Application with a Remote Server? Explain
with the help of suitable example

To communicate with a remote server, applications use network requests (usually


HTTP/HTTPS) to send data to or receive data from the server. This is commonly done
through APIs such as REST APIs.

Steps to Communicate with a Remote Server:

1. Make an HTTP request (GET, POST, etc.)


2. Send data if needed (e.g., in POST requests)
3. Receive and process the response (usually in JSON format)
4. Update the UI or database based on the response

Example: Communicating with a Remote Server in Android

Let’s say you want to fetch user data from a server using a GET request.

Using Android's HttpURLConnection


public class NetworkTask extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... voids) {
String result = "";
try {
URL url = new URL("https://example.com/api/users");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

// Read the response


InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null) {
result += line;
}

reader.close();
inputStream.close();
connection.disconnect();

} catch (Exception e) {
e.printStackTrace();
}
return result;
}

67
@Override
protected void onPostExecute(String result) {
// Process the JSON result (e.g., show in UI)
Log.d("ServerResponse", result);
}
}

Then call it in your activity:

new NetworkTask().execute();

Using Retrofit (Better and Modern Approach)


public interface ApiService {
@GET("users")
Call<List<User>> getUsers();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();

ApiService apiService = retrofit.create(ApiService.class);


Call<List<User>> call = apiService.getUsers();

call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()) {
List<User> users = response.body();
// Use the data
}
}

@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.e("API Error", t.getMessage());
}
});

Conclusion:

Communication with a remote server is done via HTTP requests using APIs. In Android,
you can use built-in classes like HttpURLConnection, or modern libraries like Retrofit or
Volley to simplify network communication.

68
7.Explain the procedure for generating API key for displaying google map in your
application.
Android allows us to integrate Google Maps in our application. For this
Google provides us a library via Google Play Services for using maps. In
order to use the Google Maps API, you must register your application on the
Google Developer Console and enable the API.

Steps for Getting Google Maps API Key

An API key is needed to access the Google Maps servers. This key is free and
you can use it with any of your applications. If you haven’t created project,
you can follow the below steps to get started:

Step 1: Open Google developer console and sign in with your Gmail
account: https://console.developers.google.com/project

Step 2: Now create new project. You can create new project by clicking on
the Create Project button and give name to your project.

Step 3: Now click on APIs & Services and open Dashboard from it.

Step 4: Now click Enable APIS AND SERVICES.

Step 5: Now search for Google Map Android API and enable it.

69
Step 6: Now refresh page and go to Credentials.

Step 7: Now click on Create credentials and choose API key. It will create API key to
integrate maps in your application
Step 8: Now API your API key will be generated. Copy it and save it
somewhere as we will need it when implementing Google Map in our
Android project.
Developing Google Maps Application in Android
Following are the steps for integrating google maps in

your application:

Step 1: Add following permission in your manifest file.

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

Step 2: Add your generated API Key in your manifest file inside application tag as
follows.

70
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCWIdlyqlFhC7lOthG164H42heV1F7N3v0" />

Step 3: Add following dependency in build.gradle file .

dependencies {
...
...
implementation 'com.google.android.gms:play-services-maps:15.0.1' }

Step 4: Now create layout resource file to display google map.

map_activity.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"
xmlns:tools="http://schemas.android.com/tools">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragm
ent" tools:context=".MapsActivity"
android:layout_width="match_parent"

36
android:layout_height="match_parent" />

</RelativeLayout>

Step 5: Now finally create an Activity by implementing

71
OnMapReadyCallback interface. MapsActivity.java

public class MapsActivity extends AppCompatActivity implements


OnMapReadyCallback { GoogleMap mMap;
@Override
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.map_activity);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment).
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Adding latitude and longitude
LatLng location = new LatLng(26.644096, 87.989391); //Adding red
marker to point location
mMap.addMarker(new MarkerOptions().position(location).
title("Marker in Birtamode"));
//Moving camera to desired location
mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); //Adding
zoom effect
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f) ); }

72

You might also like