Mobile Programming Lab Report
Mobile Programming Lab Report
(Tribhuvan University)
Kamaladi Mod, Kathmandu
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
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.
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.
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.
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
5
Version Name Release Year Key Features
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.
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>
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;
}
Step 2: Create the XML Layout File
🔹 res/layout/activity_main.xml
<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.
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.
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:
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:
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.
16
layout_constraintTop_toBotto Align the top of the
mOf desired view to the
bottom of another.
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:
<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
<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.
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:
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:
20
android:background – Background color or drawable.
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:
5. ImageView
Used to display images from drawable resources or URLs.
Major Attributes:
android:scaleType – How the image should be resized (fit Center, center Crop)
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.
<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" />
22
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full Name"
android:inputType="textPersonName" />
<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>
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" />
</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.
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.
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.
<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>
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.
startActivity(i);
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>
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.*;
@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();
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
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.
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.
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;
@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>
a) activity_main.xml
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
<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
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
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
45
FragmentManager fragmentManager =
getSupportFragmentManager();
fragmentTransaction.commit();
}
}
}
e) FragmentOne.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.
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.
49
3. What do you mean by RecyclerView? Explain its features.
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.
50
Example of ListView:
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:
<GridView
android:layout_width="match_parent"
android:id="@+id/mygrid"
android:numColumns="3"
android:layout_height="match_parent" />
</RelativeLayout>
Example of ListView:
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:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
52
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
student_item.xml
<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
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;
@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);
}
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;
@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
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 of SQLite:
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:
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.
60
private static final String DATABASE_NAME = "StudentDB.db";
// Constructor
@Override
"age INTEGER)";
db.execSQL(query);
@Override
onCreate(db);
61
Using helper class in a activity
MyDatabaseHelper dbHelper;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Establishing connection
values.put("name", "John");
values.put("age", 21);
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.
// Constructor
// onCreate() is called when the database is created for the first time
@Override
"age INTEGER)";
63
}
@Override
onCreate(db);
You can now create an instance of the database helper class in your activity or fragment.
MyDatabaseHelper dbHelper;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// This line creates or opens the database and calls onCreate() if it doesn't exist
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.
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:
These are APIs that allow communication over the web using HTTP.
Example: REST API, SOAP API, GraphQL API
Most common.
Uses HTTP methods like GET, POST, PUT, DELETE.
Returns data in JSON or XML format.
Simple and fast.
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.
4. Partner APIs
Conclusion:
66
6. How Do You Communicate Your Application with a Remote Server? Explain
with the help of suitable example
Let’s say you want to fetch user data from a server using a GET request.
@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");
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);
}
}
new NetworkTask().execute();
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.
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 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:
<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" />
dependencies {
...
...
implementation 'com.google.android.gms:play-services-maps:15.0.1' }
map_activity.xml
36
android:layout_height="match_parent" />
</RelativeLayout>
71
OnMapReadyCallback interface. MapsActivity.java
@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