Mobile Computing Using Android and iPhone (Core) (1) - Copy
Mobile Computing Using Android and iPhone (Core) (1) - Copy
6. Define Activity.
➢ A single screen in an Android app for user interaction.
1
➢ Android Intents are used to communicate between components in Android,
such as activities, services, and broadcast receivers. There are two main types:
Implicit Intents and Explicit Intents. Here are some commonly used intents:
1) ACTION_VIEW: Opens a URL or shows data to the user.
2) ACTION_DIAL: Opens the dialer with a phone number.
3) ACTION_SEND: Shares data like text, email, or files.
4) ACTION_CAMERA_BUTTON: Starts the camera.
5) ACTION_SENDTO: Sends data to a specified URI (e.g., SMS).
6) ACTION_PICK: Selects a contact or file from storage.
7) ACTION_MAIN: Launches the main entry point of an application.
8) ACTION_CALL: Makes a phone call (requires permission).
9) ACTION_BATTERY_LOW: Broadcasts when the battery is low.
10) ACTION_PACKAGE_ADDED: Broadcasts when a new app is installed.
➢ Explanation of ACTION_VIEW
➢ Purpose: The ACTION_VIEW intent is used to display content to the user. It
allows opening a webpage, viewing a map location, or displaying any URI-
based data using the appropriate application.
➢ Example: Open a Webpage
➢ What Happens:
o The intent requests the system to handle the action (view a webpage).
o The system identifies applications installed on the device that can
handle the intent (e.g., a web browser).
o The user selects an app to open the URL, and the content is displayed.
➢ This mechanism promotes reusability and flexibility by letting apps share
functionality without needing direct dependencies.
2
o Specifies all the components of the application, such as activities,
services, broadcast receivers, and content providers.
o Example:
➢ 2) Defines Permissions:
o Declares the permissions that the app needs to access device features
(e.g., internet, camera, location).
o Example:
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" />
➢ 4) Controls App Entry Point:
o Specifies the main activity to be launched when the app starts.
o Example:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
3
<receiver android:name=".MyBroadcastReceiver" />
<uses-sdk android:minSdkVersion="21"
android:targetSdkVersion="33" />
4
o Using an emulator, developers can experiment with different app
features, settings, and configurations without affecting any physical
device.
➢ No Need for Physical Device:
o Emulators provide an alternative for developers when they don't have
access to a physical Android device, making development more
accessible.
➢ Android emulators, such as the one provided by Android Studio (Android
Virtual Device or AVD), are the most commonly used tools in Android
development for these purposes.
5
➢ In summary, onStart() prepares the activity for visibility, while onResume()
prepares the activity for interaction.
➢ Resource Access:
6
o Context provides access to application resources such as strings,
layouts, and drawable files.
o Example:
String appName =
context.getResources().getString(R.string.app_name);
➢ Inflating Views:
o You can use Context to inflate layouts into views, which allows you to
create the user interface dynamically.
o Example:
➢ Launching Activities:
o Context is used to start new activities or services from the current
component.
o Example:
➢ Types of Context:
o ApplicationContext: A Context tied to the application's lifecycle, it can
be used globally across the app.
o Activity Context: A Context specific to an Activity, often used for UI-
related operations.
➢ In summary, Context is essential for accessing resources, services, and other
components in an Android app. It provides a link to the system's resources
and allows interaction with the Android framework.
7
o Examples: Icons, buttons, and backgrounds.
➢ 2) Layout Resources
o Define the app's UI structure using XML files.
o Example: activity_main.xml for arranging views like TextView, Buttons,
etc.
➢ 3) String Resources
o Store text strings to support internationalization.
o Example: strings.xml for app labels or messages.
➢ 4) Color Resources
o Define color values used in the app.
o Example: colors.xml to specify theme or text colors.
➢ 5) Dimension Resources
o Store size values like padding, margin, or font size.
o Example: dimens.xml for consistent sizing.
➢ 6) Menu Resources
o Define menus like options or context menus.
o Example: menu.xml for app navigation items.
➢ These resources enhance app scalability, maintainability, and localization.
8
➢ 5) App Entry Point
o Defines the launcher activity (main entry point) for the app.
o Example: <intent-filter>...</intent-filter> for home screen access.
➢ 6) App Permissions and Security
o Helps in defining app security policies, permissions, and user
authentication requirements.
➢ The manifest file acts as a bridge between the Android system and the app,
ensuring the app runs smoothly and adheres to system requirements.
9
➢ The Android SDK is the foundation for Android app development, enabling
developers to build robust, feature-rich applications.
11. What is android manifest file? How it is useful in developing android apps?
➢ The Android Manifest file is an essential XML file in every Android app. It is
named AndroidManifest.xml and resides in the root directory of the app
project. This file provides important information to the Android system about
the app, including its components, requirements, and permissions.
➢ Usefulness of the Android Manifest File in App Development:
➢ 1) App Identification
10
o Specifies the app's package name, which acts as a unique identifier for
the app on the Play Store and devices.
o Example: <manifest package="com.example.myapp">.
➢ 2) Component Registration
o Declares all components of the app, such as activities, services,
broadcast receivers, and content providers.
o Example: <activity android:name=".MainActivity" />.
➢ 3) Permissions Declaration
o Lists the permissions required by the app to access sensitive device
features like the internet, camera, or location.
o Example: <uses-permission
android:name="android.permission.INTERNET" />.
➢ 4) Hardware and Software Features
o Specifies hardware or software features needed by the app, ensuring it
only runs on compatible devices.
o Example: <uses-feature android:name="android.hardware.camera" />.
➢ 5) App Entry Point
o Defines the main entry point of the app using an intent filter for the
launcher activity.
o Example:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
11
12. Explain in detail: Permissions
➢ Permissions in Android are a mechanism that allows apps to request access to
sensitive device resources or user data, such as the camera, location, contacts,
or internet. This system ensures user privacy and security by granting control
over which features an app can use.
➢ Types of Permissions:
➢ 1) Normal Permissions
o These permissions allow access to less sensitive data or features and
are automatically granted at install time.
o Example: Accessing the internet or setting the wallpaper.
o Example in AndroidManifest.xml
➢ 2) Dangerous Permissions
o Required for accessing sensitive user data or device features.
o These must be explicitly granted by the user during runtime.
o Examples: Accessing location, camera, or contacts.
o Grouped into categories such as:
o Location: ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION
o Camera: CAMERA
o Contacts: READ_CONTACTS, WRITE_CONTACTS
➢ 3) Special Permissions
o These include highly sensitive operations that require additional
approval from the user.
o Example: SYSTEM_ALERT_WINDOW for displaying overlays,
WRITE_SETTINGS for modifying system settings.
➢ How Permissions Work
➢ 1) Declare in Manifest File
o Permissions must first be declared in the AndroidManifest.xml file.
o Example:
➢ 2) Request at Runtime
o For dangerous permissions, developers must request them during
runtime (Android 6.0 and above).
o Example in Java/Kotlin:
12
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CODE);
}
13
o An Activity represents a single screen in the app (e.g., login screen,
home screen). Activities are used to interact with users and display UI
elements such as buttons, text fields, etc.
o Example: MainActivity.java or MainActivity.kt
➢ 3) Services
o Services are background components that perform long-running tasks
like downloading files, playing music, or syncing data, without a user
interface.
o Example: MusicService.java
➢ 4) Resources
o Resources are files that help in building the UI and other aspects of the
app. These include layouts, strings, images, colors, and dimensions.
Resources are usually stored in the res/ directory.
o Example: res/layout/activity_main.xml for UI design,
res/values/strings.xml for text strings.
➢ 5) Code (Java/Kotlin Files)
o The Code files (written in Java or Kotlin) contain the app's logic and
functionality. They define how the app behaves and interacts with the
system and user. The main activity file (MainActivity.java or
MainActivity.kt) controls the UI elements and event handling.
o Example: MainActivity.java for handling user interaction, UI updates.
➢ 6) Resources and Layout Files
o Layout files define how the app's UI looks. These files are typically XML
files and contain components like buttons, text fields, and images.
o Example: res/layout/activity_main.xml
➢ 7) Other Components
o Broadcast Receivers, Content Providers, and other supporting classes
that handle system-wide events and allow data sharing between apps.
o Example: A BroadcastReceiver listens for events like when the device is
charging or when Wi-Fi is connected.
➢ The anatomy of an Android application includes the Manifest file, activities,
services, resources, and code files, all of which work together to provide a
smooth and functional user experience. The app's components interact with
each other to create a cohesive application that runs effectively on Android
devices.
14
stored in the res/ directory of the app project and make it easier to maintain
and customize the app's design for different devices, orientations, or
localizations.
➢ Various Layout Resources: Layout resources are XML files stored in the
res/layout/ folder. They define the structure and arrangement of UI
components like buttons, text views, and images in an activity or fragment.
Below are the common types of layout resources:
➢ 1) Linear Layout
o Arranges child views in a single direction, either vertically or
horizontally.
o Example:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:text="Hello" />
<Button android:text="Click Me" />
</LinearLayout>
➢ 2) Relative Layout
o Places child views relative to each other or to the parent container.
o Example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_alignParentTop="true"
android:text="Button 1" />
<Button
android:layout_below="@id/button1"
android:text="Button 2" />
</RelativeLayout>
➢ 3) Constraint Layout
o A flexible layout that positions views using constraints relative to other
views or the parent container. It is efficient for designing complex UIs.
o Example:
15
<ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="Click Me" />
</ConstraintLayout>
➢ 4) Frame Layout
o A simple layout where child views are stacked on top of each other. The
most recently added view is displayed on top.
o Example:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:src="@drawable/background" />
<TextView android:text="Overlay Text" />
</FrameLayout>
➢ 5) Table Layout
o Organizes child views in rows and columns, like a table.
o Example:
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView android:text="Row 1, Column 1" />
<TextView android:text="Row 1, Column 2" />
</TableRow>
<TableRow>
<TextView android:text="Row 2, Column 1" />
<TextView android:text="Row 2, Column 2" />
</TableRow>
16
</TableLayout>
➢ 6) Grid Layout
o Divides the screen into a grid of rows and columns to place child views.
o Example:
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2">
<Button android:text="Button 1" />
<Button android:text="Button 2" />
</GridLayout>
➢ 2) Implicit Intent
o Used when the target component is not specified. Instead, the system
resolves the intent by matching the action and data specified.
17
o Commonly used for performing system-defined tasks like opening a
web page, making a call, or sending an email.
o Example:
➢ 3) ACTION_DIAL
o Opens the dialer app with a number pre-filled.
o Example:
➢ 4) ACTION_PICK
o Selects data like a contact or photo from the device.
o Example: Choose a contact.
➢ Key Components of an Intent
o Action: Specifies the task to be performed (e.g., ACTION_VIEW).
o Data: URI or data associated with the action (e.g., a web URL).
o Extras: Additional data sent using key-value pairs.
o Category: Provides additional information about the action (e.g.,
CATEGORY_LAUNCHER).
➢ Intents are a vital part of Android development, enabling seamless
communication between app components and other apps. By using explicit
18
and implicit intents, developers can create dynamic and user-friendly
applications.
➢ 2) Implicit Intent
o Does not specify the target component. Instead, the system determines
the component based on the intent's action and data.
o Example: Open a webpage in a browser.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
➢ Common Uses of Intents
➢ 1) Start an Activity
o Used to move between app screens.
o Example:
➢ 2) Start a Service
o Used to perform background tasks.
o Example:
19
➢ 3) Broadcast Messages
o Sends messages to broadcast receivers.
o Example:
2. What is a fragment?
➢ A modular section of an activity.
20
5. We can select multiple options in Radio Group: True/False
➢ False
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
21
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.ProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
determinateProgressBar = findViewById(R.id.determinateProgressBar);
22
Handler handler = new Handler();
handler.postDelayed(() -> {
determinateProgressBar.setProgress(75); // Update progress
}, 2000);
}
}
➢ Explanation
o Determinate ProgressBar: Shows the progress of a task from 0 to 100%
with a visual bar.
o Indeterminate ProgressBar: Displays a spinning animation, useful for
tasks with an unknown duration.
➢ ProgressBars are helpful for enhancing user experience by providing visual
feedback during task execution. They can be used in both determinate and
indeterminate modes based on the task requirements.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
23
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name:" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
➢ Explanation
➢ 1) Orientation Attribute:
o android:orientation="vertical" arranges child views vertically.
o android:orientation="horizontal" arranges child views horizontally.
➢ 2) Child Views: Each child is aligned in sequence based on the orientation.
➢ Advantages of Linear Layout
o Simple to use and understand.
o Great for basic layouts like forms or lists.
➢ Disadvantages
o Inefficient for complex designs as it may require nesting, leading to
slower performance.
➢ Linear Layout is best used for straightforward, sequential arrangements of
views in a single direction, making it ideal for forms, menus, or other simple UI
elements.
24
translating, or fading) to a view over a specified period of time. It doesn't
require a lot of resources or complex setup, making it suitable for simple UI
animations. Tweened animations are created by defining the start and end
states of the animation, and the system interpolates the values in between.
➢ Key Components of Tweened Animation
➢ 1) Animation Types
o Translate: Moves the object from one position to another.
o Scale: Changes the size of the object.
o Rotate: Rotates the object around a pivot point.
o Alpha: Changes the transparency (fade in/out) of the object.
➢ 2) Animation Interpolators
o Interpolators define the timing curve of the animation. They control the
speed at which the animation progresses, making it smoother or more
abrupt.
o Common interpolators:
o LinearInterpolator: Constant speed throughout the animation.
o AccelerateInterpolator: Starts slow and speeds up.
o DecelerateInterpolator: Starts fast and slows down.
➢ Example of Tweened Animation
➢ XML Animation File (res/anim/rotate.xml)
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
25
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
26
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select your gender:"
android:textSize="18sp" />
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
<RadioButton
android:id="@+id/radioOther"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Other" />
</RadioGroup>
<Button
android:id="@+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
27
android:text="Submit" />
</LinearLayout>
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
submitButton = findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId != -1) {
RadioButton selectedRadioButton = findViewById(selectedId);
String choice = selectedRadioButton.getText().toString();
Toast.makeText(MainActivity.this, "You selected: " + choice,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Please select an option",
Toast.LENGTH_SHORT).show();
}
}
28
});
}
}
➢ Explanation
o RadioGroup: Contains three RadioButtons (Male, Female, Other).
o Event Handling: The OnClickListener for the button retrieves the
selected RadioButton ID and displays the choice using a Toast.
o Validation: Ensures the user selects an option before proceeding.
➢ Output
o The app shows a list of gender options.
o Upon selecting an option and clicking the "Submit" button, the
selected choice is displayed as a toast message.
➢ RadioGroup simplifies the process of managing mutually exclusive
RadioButtons, making it ideal for implementing single-choice selection in
Android applications.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
29
android:id="@+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Relative Layout Example"
android:textSize="18sp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp" />
➢ Explanation
➢ Parent Alignment:
o android:layout_centerHorizontal="true" centers the title text
horizontally in the parent.
➢ Sibling Relationships:
o android:layout_below="@id/titleText" places the EditText and Button
below the title.
o android:layout_alignParentEnd="true" aligns the button to the right
side of the parent.
➢ Flexible Layout:
o RelativeLayout allows positioning without requiring nested layouts,
reducing complexity.
30
➢ RelativeLayout is a powerful and flexible layout in Android, suitable for
creating complex and dynamic UI designs by defining relationships between
views. It minimizes nested layouts, improving performance and readability.
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
31
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
➢ Explanation
➢ XML Drawable File:
o The animation-list tag defines a series of frames (frame1, frame2, etc.),
with each frame displayed for 100 milliseconds.
➢ Java Code:
o The AnimationDrawable class is used to manage and play the frame-
by-frame animation.
o The start() method initiates the animation once the frames are set.
➢ Advantages of Frame-by-Frame Animation
o Simple and Easy to Implement: Ideal for basic animations with a limited
number of frames.
o Effective for Static Graphics: Great for games or apps where simple
character movements or visual effects are required.
➢ Disadvantages
o Resource-Intensive: Can consume a lot of memory and processing
power if many frames are used.
o Limited Flexibility: Not suitable for complex animations like moving
objects or transformations.
➢ Frame-by-frame animation is a simple method of animating static images by
displaying them in sequence. It's useful for basic visual effects and simple
32
character animations but may not be as efficient or flexible as other types of
animation for more complex scenes.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
33
➢ Java Code (MainActivity.java)
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
crossFade();
}
// Fade in animation
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(1000); // 1 second
34
imageView2.setVisibility(View.VISIBLE);
}
}
➢ Explanation
➢ AlphaAnimation:
o AlphaAnimation(1, 0) creates a fade-out effect by reducing opacity
from 1 (fully visible) to 0 (invisible).
o AlphaAnimation(0, 1) creates a fade-in effect by increasing opacity from
0 (invisible) to 1 (fully visible).
➢ Animation Duration:
o Both animations last for 1 second (1000 milliseconds) to ensure a
smooth transition.
➢ Visibility Management:
o The setVisibility() method ensures the views are properly displayed or
hidden after the animation.
➢ Advantages of Cross Fading
o Enhances user experience by providing smooth transitions.
o Simple to implement and integrate into UI designs.
➢ Cross fading is an effective animation technique to smoothly transition
between two views in Android. It improves UI aesthetics, especially in cases
like image sliders, transitions, or dynamic content updates.
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
35
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation");
builder.setMessage("Do you want to proceed?");
// Positive Button
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You selected Yes",
Toast.LENGTH_SHORT).show();
}
});
// Negative Button
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You selected No",
Toast.LENGTH_SHORT).show();
}
});
➢ Explanation
➢ Builder Pattern:
36
o AlertDialog.Builder is used to construct the dialog by setting the title,
message, and buttons.
➢ Buttons:
o Positive Button: Executes an action when "Yes" is clicked.
o Negative Button: Executes an action when "No" is clicked.
➢ Toast Messages:
o Displays feedback when a button is clicked.
➢ Dialogs like AlertDialog provide a convenient way to interact with users for
confirmations, warnings, or simple information. They are versatile and easy to
implement in Android applications.
37
o Confirmation: Seek user approval for critical actions (e.g., delete,
logout).
o Input Collection: Gather simple data such as dates, times, or basic user
input.
o User Feedback: Show progress, success messages, or error information.
➢ Example: Simple AlertDialog
Attribute Description
android:stretchColumns Specifies which columns should expand to fill
available space.
android:shrinkColumns Specifies which columns should shrink if space
is limited.
38
android:collapseColumns Hides specific columns without removing them
from the layout.
android:padding Sets the padding for the entire TableLayout.
android:layout_width Defines the width of the TableLayout (e.g.,
match_parent or wrap_content).
android:layout_height Defines the height of the TableLayout (e.g.,
match_parent or wrap_content).
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
39
</TableLayout>
➢ TableLayout is a useful view group for displaying content in a structured row-
column format. By leveraging attributes like stretchColumns and
shrinkColumns, developers can create flexible and responsive table-based
layouts.
➢ https://www.geeksforgeeks.org/android-tablelayout/
➢ https://www.tutorialspoint.com/android/android_table_layout.htm
➢ https://developer.android.com/guide/topics/ui/layout/grid
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
40
➢ Fragment Class (ExampleFragment.java)
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the fragment's layout
return inflater.inflate(R.layout.fragment_example, container, false);
}
}
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
41
➢ Fragments enhance reusability by enabling modular design, dynamic layouts,
and code reuse. This reduces development effort, ensures consistency, and
allows apps to adapt seamlessly to various devices and screen sizes.
<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">
42
<!-- Radio Group for Gender -->
<RadioGroup
android:id="@+id/radioGroupGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:marginTop="16dp">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
43
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize UI elements
editTextName = findViewById(R.id.editTextName);
radioGroupGender = findViewById(R.id.radioGroupGender);
buttonSubmit = findViewById(R.id.buttonSubmit);
textViewGreeting = findViewById(R.id.textViewGreeting);
44
textViewGreeting.setText("Hello " + name + "! You selected " +
gender + ".");
} else {
textViewGreeting.setText("Please enter your name and select a
gender.");
}
}
});
}
}
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:textStyle="bold"
android:padding="8dp" />
45
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grade"
android:textStyle="bold"
android:padding="8dp" />
</TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="20"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
android:padding="8dp" />
</TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
46
android:text="22"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B"
android:padding="8dp" />
</TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="21"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
android:padding="8dp" />
</TableRow>
</TableLayout>
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
47
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
➢ Explanation
➢ TableLayout Attributes:
o android:stretchColumns="1": Ensures that the second column expands
to fill available space.
o android:padding="16dp": Adds padding around the table.
➢ Structure:
o Each row is defined using the <TableRow> tag.
o The first row contains headers (Name, Age, Grade), styled with bold
text.
o Subsequent rows contain data for students.
➢ Reusability:
o Add or remove rows dynamically in the XML or programmatically if
needed.
➢ This example demonstrates how to use TableLayout to create a structured
tabular UI in Android applications, perfect for displaying data in a grid format.
48
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1000" />
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize ImageView
ImageView imageView = findViewById(R.id.imageView);
49
// Set OnClickListener to trigger animation
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.startAnimation(twinedAnimation);
}
});
}
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_centerInParent="true" />
</RelativeLayout>
➢ Explanation
➢ Animation File:
o Combines rotate and scale animations.
o The object rotates 360 degrees while scaling up to 1.5x its size and
back.
➢ Trigger Animation:
o The animation starts when the user clicks on the ImageView.
➢ Effect:
o The object rotates and scales simultaneously, creating a dynamic visual
effect.
➢ Twined Animation in Android provides a simple way to combine multiple
animation effects, making the app visually appealing and interactive.
50
4. List various UI Screen Elements. Explain any two with example.
➢ TextView: Displays text.
➢ EditText: Allows user input.
➢ Button: Represents a clickable button.
➢ ImageView: Displays images.
➢ CheckBox: Represents a selectable option.
➢ RadioButton: Allows selection of a single option within a group.
➢ Spinner: Provides a dropdown menu for selection.
➢ Switch: Toggles between ON and OFF states.
➢ SeekBar: Allows sliding to select a value.
➢ ProgressBar: Displays progress.
➢ Explanation of Two UI Elements
➢ 1. TextView
o Description: A basic UI element that displays text to the user.
o Attributes:
▪ android:text: Sets the text to display.
▪ android:textSize: Adjusts the font size.
▪ android:textColor: Changes the text color.
o Example:
<TextView
android:id="@+id/textViewExample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:textSize="20sp"
android:textColor="#FF5722" />
➢ 2. Button
o Description: A clickable UI element that triggers an action when
pressed.
o Attributes:
▪ android:text: Sets the button's label.
▪ android:onClick: Specifies the method to invoke when the
button is clicked.
o Example:
o XML Layout:
<Button
android:id="@+id/buttonExample"
51
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!" />
o Java Code:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
52
o Example: Move an object 100 pixels to the right.
<translate
android:fromXDelta="0"
android:toXDelta="100"
android:duration="500" />
➢ 2) Rotate Animation
o Rotates an object around a specified pivot point.
o Attributes: fromDegrees, toDegrees, pivotX, pivotY.
o Example: Rotate an object 360 degrees.
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1000" />
➢ 3) Scale Animation
o Changes the size of an object, either increasing or decreasing.
o Attributes: fromXScale, toXScale, fromYScale, toYScale.
o Example: Scale an object to twice its size.
<scale
android:fromXScale="1.0"
android:toXScale="2.0"
android:fromYScale="1.0"
android:toYScale="2.0"
android:duration="500" />
➢ 4) Alpha Animation
o Modifies the transparency of an object.
o Attributes: fromAlpha, toAlpha.
o Example: Fade out an object.
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="500" />
53
➢ 5) Combination of Animations (Set Animation)
o Combines multiple animations to run together or sequentially.
o Useful for creating complex effects.
o Example: Rotate and scale an object simultaneously.
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:duration="1000" />
<scale
android:fromXScale="1.0"
android:toXScale="1.5"
android:fromYScale="1.0"
android:toYScale="1.5"
android:duration="1000" />
</set>
<GridLayout
54
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="4"
android:columnCount="4"
android:padding="16dp"
android:useDefaultMargins="true">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="DEL" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="/" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="8" />
55
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="9" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="x" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="5" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="6" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="-" />
56
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="1" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="2" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="3" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:text="+" />
</GridLayout>
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
57
}
}
58
➢ UPDATE
9. What is Retrofit?
➢ A library for networking operations in Android.
content://com.android.contacts/contacts
➢ Querying Contacts
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.appcompat.app.AppCompatActivity;
@Override
59
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("Contact Name: " + displayName);
}
cursor.close();
}
}
}
➢ Explanation
o URL: content://com.android.contacts/contacts is used to fetch contacts.
o Query: The getContentResolver().query() method fetches data from the
specified content provider URL.
o Cursor: The result is processed row by row using a cursor.
➢ A Content Provider URL simplifies accessing structured data from apps or
shared resources, making it a critical component for Android data-sharing
operations.
60
reduces boilerplate code. This makes the process of making API calls and
handling responses cleaner and more maintainable.
➢ Asynchronous and Synchronous Requests: Retrofit supports both synchronous
and asynchronous network calls, providing flexibility in handling background
tasks or UI updates.
➢ JSON Parsing: Retrofit can automatically parse JSON responses into Java
objects using libraries like Gson or Moshi, which eliminates the need for
manually parsing data.
➢ Error Handling: It provides easy handling of errors (e.g., HTTP errors or parsing
issues) via built-in error models, making the development process smoother
and more robust.
➢ Customizable: Retrofit is highly customizable and can be configured with
custom converters, interceptors, and client settings, allowing developers to
adjust it to fit specific needs.
➢ Interceptors and Logging: Retrofit integrates well with OkHttp, enabling
features such as logging, monitoring, or modifying network requests and
responses using interceptors.
➢ Support for Authentication: Retrofit can handle authentication strategies, such
as Basic Auth or OAuth, for secure communication with APIs.
➢ Integration with other Libraries: Retrofit can be seamlessly integrated with
other Android libraries like RxJava or Kotlin Coroutines for asynchronous
programming and handling the flow of data.
➢ Overall, Retrofit streamlines network communication in Android apps,
improves code readability, and reduces development time.
61
o beginTransaction(): Begins a database transaction.
o setTransactionSuccessful(): Marks a transaction as successful.
o endTransaction(): Ends a database transaction.
o close(): Closes the database connection.
o isOpen(): Checks if the database is open.
o getVersion(): Retrieves the version of the database.
o setVersion(): Sets the version of the database.
➢ Explanation of a Method: insert()
➢ The insert() method is used to insert a new row into a specified table in the
SQLite database. It takes the name of the table, an optional column name for
the default value (if no value is provided for a column), and a ContentValues
object that contains the column-value pairs to insert.
➢ Syntax:
o In this example, a new row is inserted into the users table with the
values "John Doe" for the name column and 30 for the age column.
o The method returns the row ID of the newly inserted row if the
insertion was successful, or -1 if the insertion failed.
➢ This method makes it easy to insert data into a database without needing to
manually write SQL statements.
62
resides in the app's own database or external sources like contacts, media, or
calendar.
➢ Key Points:
o Interacts with Content Providers: ContentResolver accesses shared data
stored in content providers (e.g., contacts, media files).
o URI-based: It uses URIs to identify specific data to be accessed or
modified.
o Methods: Common methods include insert(), update(), delete(), and
query() to perform CRUD operations.
o Permissions: Access to content providers often requires appropriate
permissions, ensuring secure data access.
➢ Example:
o To query contacts using ContentResolver:
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
o IF EXISTS ensures that the query does not throw an error if the table
does not exist.
➢ Example: Deleting a Table in Android SQLite
➢ 1. Using SQLiteOpenHelper Class
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Employee"); // Deleting Employee table
onCreate(db); // Recreating the table
}
63
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS Employee");
64
editor.apply();
@Override
public boolean onCreate() {
DBHelper dbHelper = new DBHelper(getContext());
database = dbHelper.getWritableDatabase();
return database != null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[]
selectionArgs, String sortOrder) {
return database.query(TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
}
65
@Override
public Uri insert(Uri uri, ContentValues values) {
long id = database.insert(TABLE_NAME, null, values);
return Uri.withAppendedPath(uri, String.valueOf(id));
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return database.delete(TABLE_NAME, selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[]
selectionArgs) {
return database.update(TABLE_NAME, values, selection, selectionArgs);
}
}
➢ A Content Provider allows Android apps to share data securely and provides a
structured way to manage and access shared data.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
66
import retrofit2.Call;
import retrofit2.http.GET;
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
➢ Retrofit is a powerful HTTP client for Android that simplifies API calls, handles
JSON conversion, and supports authentication.
67
➢ A REST API (Representational State Transfer API) allows communication
between a client and a server using standard HTTP methods. It is widely used
for web and mobile applications to exchange data efficiently.
➢ Basic Uses of REST API:
➢ 1. Data Retrieval (GET Request)
o Fetch data from a server.
o Example: A weather app uses a REST API to get temperature details.
o Example API call: GET https://api.weather.com/current?city=Delhi
➢ 2. Creating Data (POST Request)
o Send new data to the server (e.g., user registration).
o Example API call
POST https://api.example.com/users
Content-Type: application/json
{
"name": "John",
"email": "john@example.com"
}
68
➢ SQLite supports the following five storage classes for storing data:
package com.example.mydatabaseapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
69
// Database Name and Version
private static final String DATABASE_NAME = "MyDatabase.db";
private static final int DATABASE_VERSION = 1;
@Override
public void onCreate(SQLiteDatabase db) {
// Execute table creation query
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop the old table if it exists and create a new one
db.execSQL("DROP TABLE IF EXISTS Employee");
onCreate(db);
}
}
package com.example.mydatabaseapp;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
import androidx.appcompat.app.AppCompatActivity;
DBHelper dbHelper;
70
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
➢ Explanation
o DBHelper Class – Extends SQLiteOpenHelper to create and manage the
database.
o onCreate() – Executes the SQL command to create the Employee table.
o onUpgrade() – Handles database version updates.
o getWritableDatabase() – Opens or creates the database.
71
➢ Example Usage of Cursor
Log.d("EmployeeData", "ID: " + id + ", Name: " + name + ", Salary: " +
salary);
} while (cursor.moveToNext());
}
cursor.close();
➢ The Cursor class helps navigate and read database query results efficiently. It
provides methods for moving between rows, retrieving data, and managing
memory in Android SQLite databases.
72
➢ 1. SQL Interface
o Acts as the entry point for users to interact with the database.
o Accepts SQL commands (e.g., SELECT, INSERT, UPDATE, DELETE).
o Translates these commands into operations understood by SQLite's
underlying components.
➢ 2. Tokenizer
o Breaks the SQL command into tokens (keywords, identifiers, operators,
etc.).
o Helps in parsing the SQL query efficiently.
➢ 3. Parser
o Validates the SQL query syntax using a parser generated by tools like
Lemon.
o Constructs a parse tree representing the SQL query structure.
➢ 4. Code Generator
o Converts the parse tree into a virtual machine program consisting of
SQLite bytecode.
o Bytecode instructions define how to execute the SQL query.
➢ 5. Virtual Machine (VDBE)
o The Virtual Database Engine (VDBE) interprets and executes the
bytecode generated by the code generator.
o Handles all database operations like reading/writing data.
➢ 6. B-Tree Module
o Organizes and stores database tables and indexes in a B-tree structure.
o Ensures efficient data retrieval and storage.
➢ 7. Pager Module
o Manages database pages (fixed-size chunks of data).
o Handles reading, writing, caching, and ensuring atomicity in
transactions.
➢ 8. OS Interface
o Provides an abstraction layer to interact with the underlying operating
system.
o Manages file I/O, locking mechanisms, and system resources.
➢ 9. Storage Layer
o Handles the actual storage of data in a database file on disk.
o Implements ACID (Atomicity, Consistency, Isolation, Durability)
properties to ensure reliability.
➢ This modular architecture makes SQLite portable, efficient, and suitable for
applications requiring a lightweight database solution.
+----------------------+
73
| SQL Interface | <-- User interacts with SQL queries
+----------------------+
|
v
+----------------------+
| Tokenizer | <-- Breaks SQL into tokens
+----------------------+
|
v
+----------------------+
| Parser | <-- Validates and creates parse tree
+----------------------+
|
v
+----------------------+
| Code Generator | <-- Generates bytecode instructions
+----------------------+
|
v
+----------------------+
| VDBE | <-- Executes the bytecode
| (Virtual Machine) |
+----------------------+
|
v
+----------------------+
| B-Tree Module | <-- Manages tables and indexes
+----------------------+
|
v
+----------------------+
| Pager Module | <-- Handles data pages and caching
+----------------------+
|
v
+----------------------+
| OS Interface | <-- Interacts with the operating system
+----------------------+
|
v
74
+----------------------+
| Storage Layer | <-- Stores data on disk with ACID compliance
+----------------------+
➢ https://www.sqlite.org/arch.html
{
"name": "John Doe",
"email": "john@example.com"
}
75
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
➢ 4. Statelessness
o Each API request is independent and contains all required data.
o The server does not store client session data.
➢ 5. Authentication and Security
o Common authentication methods:
▪ API Key – Unique key for identifying clients.
▪ OAuth 2.0 – Secure token-based authentication.
▪ JWT (JSON Web Token) – Encrypted token validation.
o Example Authentication Header: Authorization: Bearer
eyJhbGciOiJIUzI1...
➢ 6. Status Codes (Response Codes)
76
o Lightweight – No separate server required.
o Fast and Reliable – Optimized for mobile devices.
o ACID-Compliant – Ensures data integrity.
o Integrated with Android – Comes built-in with Android SDK.
➢ Steps to Use SQLite in Android
➢ 1. Create a Database Helper Class
o Use SQLiteOpenHelper to manage the database.
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Employee (id INTEGER PRIMARY KEY, name
TEXT, salary REAL)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Employee");
onCreate(db);
}
}
➢ 2. Insert Data into SQLite
77
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery("SELECT * FROM Employee", null);
}
➢ Advantages of SQLite
o No Configuration Required – Works out of the box.
o Supports SQL Queries – Easy to use with standard SQL commands.
o Data Persistence – Data remains even if the app is closed.
➢ SQLite is an efficient way to store structured data locally in Android apps. It is
lightweight, fast, and supports SQL queries for managing data.
3. Write a code snippet that allows the insertion and deletion of records in Stud
table managed using SQLite. Take the appropriate fields as per your choice.
4. Write an Android application to create a database with following fields: empid,
designation, basic salary, DA, HRA. Calculate Gross salary by counting DA
@20%, HRA @10% on basic salary. Show all the values in Grid for 10
employees.
5. Explain with required steps: how to create Content Provider in an android app.
➢ A Content Provider in Android is used to share data between different
applications securely. It manages access to structured data stored in
databases, files, or other sources.
78
➢ Steps to Create a Content Provider:
➢ 1. Create a Database (Optional)
o If storing data in an SQLite database, create a database helper class:
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE items (id INTEGER PRIMARY KEY, name
TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{}
}
➢ 2. Create a Content Provider Class
o Extend ContentProvider and override required methods:
static {
uriMatcher.addURI(AUTHORITY, TABLE_NAME, 1);
}
@Override
public boolean onCreate() {
database = new MyDatabaseHelper(getContext()).getWritableDatabase();
return (database != null);
}
@Override
79
public Cursor query(Uri uri, String[] projection, String selection, String[]
selectionArgs, String sortOrder) {
return database.query(TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long id = database.insert(TABLE_NAME, null, values);
return Uri.withAppendedPath(uri, String.valueOf(id));
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[]
selectionArgs) {
return database.update(TABLE_NAME, values, selection, selectionArgs);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return database.delete(TABLE_NAME, selection, selectionArgs);
}
@Override
public String getType(Uri uri) {
return "vnd.android.cursor.dir/" + AUTHORITY + "." + TABLE_NAME;
}
}
<provider
android:name=".MyContentProvider"
android:authorities="com.example.myprovider"
android:exported="true" />
80
Uri uri = Uri.parse("content://com.example.myprovider/items");
// Query data
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
// Insert data
ContentValues values = new ContentValues();
values.put("name", "New Item");
getContentResolver().insert(uri, values);
➢ A Content Provider helps share data between apps securely. The key steps
include creating a database (if needed), defining a ContentProvider class,
registering it in AndroidManifest.xml, and accessing it using ContentResolver.
SharedPreferences sharedPref =
getSharedPreferences("user_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", "JohnDoe");
editor.putBoolean("is_logged_in", true);
editor.apply();
81
o Storage Mechanism: Android stores files on the device’s internal
storage under the app’s private directory.
o File Location: The internal storage is located at
/data/data/<app_package>/files/.
o Example:
SQLiteDatabase db = openOrCreateDatabase("app_data.db",
MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY
KEY, name TEXT, email TEXT)");
82
db.execSQL("INSERT INTO users (name, email) VALUES ('John',
'john@example.com')");
83
Que-4(A) Answer the following.
84
➢ To use GPS in an Android application, follow these steps:
➢ 1. Add Permissions in Manifest
o Include the required permissions in the AndroidManifest.xml file:
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
➢ 2. Enable Location Services: Ensure the device's GPS is enabled through the
Settings.
➢ 3. Use LocationManager
o In the Java/Kotlin code, obtain the LocationManager service:
locationManager.requestLocationUpdates(LocationManager.GPS_PROV
IDER, 1000, 1, locationListener);
➢ This allows an Android app to fetch the user's GPS location.
➢ https://www.geeksforgeeks.org/how-to-get-user-location-in-android/
85
o Networking APIs allow apps to retrieve data from RESTful APIs, such as
fetching JSON or XML responses from a server.
o Example: A weather app fetching real-time weather data.
➢ 2. Sending Data to a Server
o Apps can send user data, such as form submissions or authentication
requests, to remote servers.
o Example: Sending login credentials to a backend for authentication.
➢ 3. Downloading and Uploading Files
o Networking APIs support downloading images, videos, or documents
and uploading files like profile pictures.
o Example: A cloud storage app allowing users to upload and download
files.
➢ 4. Real-time Communication
o Some networking APIs support WebSockets and push notifications for
real-time updates.
o Example: Chat applications using Firebase Cloud Messaging (FCM).
➢ Common Networking APIs in Android:
o HttpURLConnection – Basic HTTP requests.
o OkHttp – Efficient networking with caching.
o Retrofit – Simplifies API calls with JSON parsing.
o Volley – Handles network requests with caching and threading support.
➢ These APIs help in efficient and secure data exchange over the internet.
86
➢ 4. Handling USSD Requests
o Supports running USSD codes to check balance, activate services, etc.
o Example: A mobile recharge app using USSD codes to fetch account
details.
➢ Example Code: Getting SIM Operator Name
FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, location -> {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
87
}
});
➢ Why Use FLP?
o Saves battery by optimizing location updates.
o Works both indoors and outdoors.
o Provides high accuracy with minimal coding effort.
➢ FLP is widely used in location-based apps like Google Maps, ride-sharing apps,
and fitness trackers.
try {
List<Address> addresses = geocoder.getFromLocation(40.7128, -74.0060,
1);
if (addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
88
}
} catch (IOException e) {
e.printStackTrace();
}
➢ Uses of Geocoding in Android
o Map Applications (Google Maps, Uber)
o Location-based Search (Finding restaurants nearby)
o Address Autocomplete (Filling addresses in forms)
o Navigation & Tracking (GPS tracking apps)
➢ Geocoding is essential for integrating real-world locations into mobile
applications.
6. List and explain various types of APIs commonly used in web services.
➢ Web services in Android apps typically interact with APIs to fetch or send data
over the internet. These APIs come in various types, depending on their
purpose and communication methods. Below are some commonly used APIs
in Android web services:
➢ 1. REST API (Representational State Transfer)
o Overview: REST is an architectural style that uses standard HTTP
methods (GET, POST, PUT, DELETE) for communication. It is lightweight,
scalable, and stateless.
o Usage: REST APIs are the most commonly used for interacting with web
servers, as they return data in formats like JSON or XML.
o Example: Fetching product details from an e-commerce website.
o Android Implementation: Use Retrofit or Volley libraries for easy
integration with REST APIs.
➢ 2. SOAP API (Simple Object Access Protocol)
o Overview: SOAP is a protocol for exchanging structured information in
the implementation of web services. It uses XML for messaging and
operates over protocols like HTTP or SMTP.
o Usage: SOAP APIs are commonly used in enterprise-level applications
that require strict security and transactional reliability.
o Example: Payment gateway integration or enterprise system
communication.
o Android Implementation: Use KSoap2 library for working with SOAP
APIs.
➢ 3. GraphQL API
89
o Overview: GraphQL is a query language for APIs that allows clients to
request only the data they need. It offers more flexibility compared to
REST APIs, as it allows clients to specify the structure of the response.
o Usage: GraphQL is useful when you need to interact with complex
systems that involve multiple data sources or require tailored queries.
o Example: A social media app fetching user posts, comments, and likes
in a single query.
o Android Implementation: Use Apollo GraphQL library to integrate
GraphQL APIs into Android.
➢ 4. WebSocket API
o Overview: WebSockets enable two-way communication between the
client and server. It provides full-duplex communication, allowing data
to be sent and received in real time.
o Usage: WebSockets are used in real-time applications like chat apps,
live notifications, or stock market updates.
o Example: A live chat feature or a real-time multiplayer game.
o Android Implementation: Use libraries like OkHttp or Socket.IO for
WebSocket integration.
➢ 5. JSON-RPC / XML-RPC
o Overview: These are remote procedure call (RPC) protocols encoded in
JSON or XML, allowing for communication between clients and servers.
o Usage: Used in cases where you need simple, lightweight RPC
communication. JSON-RPC is more commonly used due to its
efficiency.
o Example: Payment processing or querying user data.
o Android Implementation: Use libraries like Gson (for JSON-RPC) to
integrate these APIs in Android.
➢ 6. Firebase API (Real-time Database, Firestore, Push Notifications)
o Overview: Firebase is a suite of cloud-based tools provided by Google,
which includes APIs for real-time databases, authentication, push
notifications, and more.
o Usage: Firebase is widely used for mobile apps that require real-time
data sync, push notifications, and easy backend services.
o Example: Firebase Cloud Messaging (FCM) for push notifications.
o Android Implementation: Use the Firebase SDK for integrating Firebase
services in Android apps.
➢ 7. OAuth API
o Overview: OAuth is an open standard for access delegation, commonly
used for authorization. It allows third-party applications to access user
resources without sharing their credentials.
90
o Usage: OAuth is widely used for integrating third-party login systems
(Google, Facebook) or for secure access to user data across different
services.
o Example: Google Sign-In or accessing user data on social media.
o Android Implementation: Use the Google Sign-In API or OAuth 2.0
libraries to integrate OAuth services in Android apps.
➢ These APIs provide various functionalities for Android apps, from simple data
retrieval (REST) to real-time communication (WebSocket), and authentication
(OAuth). Choosing the right API depends on the nature of your application,
whether it needs real-time updates, secure user login, or efficient data
handling. Libraries like Retrofit, Volley, Firebase, and OkHttp are commonly
used in Android to interact with these web services.
91
o Use NotificationManager to show the notification:
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(1, builder.build());
92
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapexample">
<application
... >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR_API_KEY"/>
</application>
</manifest>
➢ 2. Add Google Play Services to build.gradle
o Add the dependency for Google Play services in the build.gradle
(Module: app) file.
implementation 'com.google.android.gms:play-services-maps:17.0.0'
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
93
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,
10));
10. Explain with example: how to get current location on android app.
➢ To get the current location (latitude and longitude) of a device in Android, you
can use Location Services provided by the Android framework. The most
commonly used service is FusedLocationProviderClient (part of Google Play
Services), which combines GPS, Wi-Fi, and mobile network data to give the
most accurate location.
➢ Steps to Get Current Location:
➢ 1. Add Permissions in AndroidManifest.xml:
o You need to request location permissions to access the device's
location:
94
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
95
locationTextView = findViewById(R.id.locationTextView);
// Initialize FusedLocationProviderClient
fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
fusedLocationClient.getLastLocation()
@Override
if (location != null) {
});
96
➢ Explanation:
o FusedLocationProviderClient: This is used to access the device’s current
location.
o getLastLocation(): This method fetches the last known location of the
device. If no location is found (for example, if the device has never
obtained location data), it may return null.
o Permissions: Make sure to check if location permissions are granted in
your app (this example assumes permissions are granted).
➢ In the summary, by using the FusedLocationProviderClient from Google Play
Services, you can easily get the current location of a device in your Android
app. This approach combines GPS and network data for improved accuracy
and reliability.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
97
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
import android.os.AsyncTask;
import android.util.Log;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;
98
@Override
try {
connection.setRequestMethod("POST");
connection.setDoOutput(true);
outputStream.writeBytes(data);
outputStream.flush();
outputStream.close();
String inputLine;
99
StringBuffer response = new StringBuffer();
response.append(inputLine);
inputStreamReader.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
@Override
super.onPostExecute(result);
if (result != null) {
100
information) to a backend server (using PHP or any server-side language),
which processes the data and interacts with the MySQL database.
101
o Services like Google Maps API, Bing Maps API, or Mapbox provide
geocoding functionality. Developers can send requests to these
services and get the response in the form of coordinates or addresses.
➢ Offline Geocoding:
o Some applications use offline geocoding services, which store
geographical data locally on the device for privacy or performance
reasons.
➢ Geocoding Example:
o Using Google Maps API for Geocoding:
o In Android or web applications, you can use the Google Maps API to
perform geocoding and reverse geocoding.
o Geocoding Example (Address to Coordinates):
o Explanation:
o The Geocoder class in Android allows you to convert an address (e.g.,
“1600 Pennsylvania Ave”) to latitude and longitude using
getFromLocationName().
o The result is a list of possible addresses, and the first result (if available)
gives the exact coordinates.
➢ Reverse Geocoding Example (Coordinates to Address):
102
double longitude = -77.0365;
2. Consider an Item table, which has item id, item name and item price fields.
Write a query to fetch the items having price lower than 1000 rs. Using JSON.
➢ Here’s how you can store and query JSON data representing an Item table
with fields: item_id, item_name, and item_price.
➢ Step 1: Sample JSON Data
[
{ "item_id": 1, "item_name": "Laptop", "item_price": 50000 },
{ "item_id": 2, "item_name": "Mouse", "item_price": 700 },
{ "item_id": 3, "item_name": "Keyboard", "item_price": 900 },
{ "item_id": 4, "item_name": "USB Cable", "item_price": 150 },
{ "item_id": 5, "item_name": "Monitor", "item_price": 8000 }
]
103
o For MySQL:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.stream.Collectors;
class Item {
int item_id;
String item_name;
int item_price;
}
104
// Print the filtered items
filteredItems.forEach(item -> System.out.println(item.item_name + ": " +
item.item_price));
}
}
Output:
Mouse: 700
Keyboard: 900
USB Cable: 150
105
o Retrofit automatically parses JSON into Java objects when fetching data
from a web server.
➢ JSON is widely used in Android for handling structured data, especially when
working with REST APIs. Libraries like Gson and Retrofit make it easier to use.
106
6) Upload the APK/AAB – Submit the signed APK or AAB file to the Play
Console.
7) Review and Submit – Fill in required information, complete content
rating, and review app policies.
8) Publish the App – Click "Publish" to submit your app for Google Play
review.
9) Wait for Approval – Google reviews the app before it goes live on the
Play Store.
107
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationText = findViewById(R.id.locationText);
locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
108
// Request location updates from GPS provider
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 10, this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
protected void onPause() {
super.onPause();
// Stop receiving location updates
locationManager.removeUpdates(this);
}
}
➢ Explanation:
o Permissions: The ACCESS_FINE_LOCATION permission is required for
GPS access.
o LocationManager: This system service manages location updates.
o LocationListener: The onLocationChanged() method is called whenever
the location is updated (every 5 seconds with a minimum movement of
10 meters).
109
o Location Updates: The app displays the latitude and longitude of the
device in a TextView.
➢ In the summary, GPS is a powerful tool in Android for providing location-
based services. By using the LocationManager and LocationListener,
developers can get real-time location updates and build applications that
depend on precise positioning, such as navigation, location tracking, and
geofencing.
110
8. What is the use of button control?
➢ To trigger an action upon clicking.
9. What is a framework?
➢ A reusable set of libraries and APIs for app development.
111
➢ 3. Graphics and Animation
o Uses Core Graphics, Core Animation, and OpenGL ES for rendering
high-quality graphics.
o Enables smooth animations and transitions.
➢ 4. Data Management
o Supports Core Data for object-oriented database management.
o Allows file handling and data persistence using UserDefaults and
FileManager.
➢ 5. Multimedia Support
o Provides frameworks like AVFoundation and Core Audio for audio and
video processing.
➢ 6. Networking and Connectivity
o Supports web interactions using NSURLSession and WebKit.
o Includes built-in support for Bluetooth, Wi-Fi, and push notifications.
➢ 7. Multitasking and Background Execution
o Allows apps to run tasks in the background (e.g., downloading files,
playing music).
➢ 8. Location and Sensors
o Supports location services using Core Location.
o Provides access to device sensors like gyroscope, accelerometer, and
camera.
➢ Cocoa Touch is the backbone of iOS, iPadOS, watchOS, and tvOS app
development, providing essential libraries and tools for building modern,
responsive, and interactive applications. It simplifies UI development, user
interaction handling, multimedia processing, and networking, making it a
crucial part of the iOS ecosystem.
112
o It helps organize code into logical modules, separating business logic
or common utilities from the rest of the app.
o This modularity simplifies maintaining and updating code, as each
static library can be updated independently of the main app.
➢ 3. Performance
o Since static libraries are linked at compile-time, there is no overhead
associated with loading them at runtime, resulting in faster execution
and potentially smaller runtime memory usage.
o No dynamic loading delays as in the case with dynamic libraries, which
can improve the app’s startup time.
➢ 4. Simplified Version Control
o Static libraries make managing versions of reusable code easier
because you can track and version the library separately from your
application code.
o Developers can maintain different versions of the library and update
the app accordingly without rebuilding the entire app from scratch.
➢ 5. No Dependency on External Resources
o As static libraries are compiled into the app during build time, they do
not rely on external resources, such as other applications or libraries, at
runtime.
o This makes the app more stable, as all dependencies are included in the
final build.
➢ 6. Ease of Integration
o Once a static library is created, it can be easily added to other projects
without much configuration. This is especially useful for shared
functionality like custom UI elements, networking, or data parsing.
➢ 7. Reduced App Size (Relative to Dynamic Libraries)
o Static libraries generally result in a smaller app size compared to
dynamic libraries in certain cases, as all the required resources are
included directly in the app.
➢ Cocoa Touch Static Libraries provide a convenient way to modularize, reuse,
and manage code within iOS applications. They enable code sharing, improve
performance by eliminating runtime dependency loading, and make app
development more maintainable. However, while they have many advantages
in terms of performance and integration, they may not be suitable for all
scenarios, especially in cases where dynamic updates or sharing of libraries
across apps at runtime is needed.
4. State the main differences between text view and text field.
113
➢ Main Differences Between Text View and Text Field in iOS Development:
Scrolling Supports scrolling when the Does not support scrolling; text
text overflows. may be truncated if it exceeds
the field width.
User Allows users to enter and edit Allows users to enter only one
Interaction multiple lines of text. line of text.
➢ Conclusion
o Use UITextView when the user needs to enter or display multiple lines
of text.
o Use UITextField for single-line text inputs, such as form fields.
5. Explain: Simulator.
➢ A Simulator in iOS development is a tool provided by Xcode that allows
developers to run and test iOS applications on a virtual device without
needing a physical iPhone or iPad. It mimics the behavior of real iOS devices,
helping developers test UI, functionality, and performance.
➢ Key Features of the iOS Simulator:
➢ 1. Device Emulation
o Simulates different iOS devices, including iPhones, iPads, and Apple
Watches.
114
o Supports various screen sizes and resolutions for responsive design
testing.
➢ 2. Faster Development & Testing
o Allows developers to quickly test apps without deploying them to a
physical device.
o Speeds up debugging by providing easy access to logs, errors, and
crash reports.
➢ 3. Built-in Debugging Tools
o Supports console logs, breakpoints, and memory profiling for
identifying and fixing issues.
o Integrates with Xcode’s debugging tools for real-time testing.
➢ 4. Supports Different iOS Versions
o Developers can test their apps on different iOS versions without
needing multiple physical devices.
➢ 5. Network & Location Simulation
o Can simulate Wi-Fi, cellular network conditions, GPS locations, and
movement for location-based apps.
➢ 6. Limited Hardware Functionality
o Cannot simulate hardware-dependent features like camera, Bluetooth,
Face ID, and certain sensors (e.g., gyroscope).
o Some performance differences exist between the simulator and real
devices.
➢ The iOS Simulator is an essential tool for iOS development, enabling quick and
efficient testing without requiring a physical device. However, final testing
should always be done on real devices to ensure full functionality, especially
for hardware-dependent features.
6. What is Storyboard?
➢ A Storyboard is a visual representation of an iOS application’s user interface,
created using Interface Builder in Xcode. It allows developers to design and
manage multiple screens (ViewControllers) and define their transitions
(segues) in a single file.
➢ Graphical UI Design – Provides a drag-and-drop interface to design app
layouts without writing code.
➢ Navigation Flow – Connects multiple screens using segues, defining
transitions between ViewControllers.
➢ Auto Layout & Constraints – Supports Auto Layout for designing responsive
and adaptive interfaces.
115
➢ Real-Time Preview – Allows developers to preview UI changes instantly
without running the app.
➢ Reduces Code Complexity – Eliminates the need for manual ViewController
instantiation and navigation handling in code.
➢ In the summary, Storyboards make iOS development more intuitive by
providing a visual and structured way to design app layouts and navigation.
They are best suited for small to medium-sized apps but may require
segmentation into multiple storyboards for larger projects.
116
➢ How MVC Works Together:
➢ 1. User Interaction:
o The user interacts with the View (e.g., tapping a button).
➢ 2. Controller Handles Action:
o The View informs the Controller of the user’s action.
o The Controller processes the action and updates the Model (e.g.,
adding an item to the shopping cart).
➢ 3. Model Updates Data:
o The Model updates the data (e.g., changing the cart contents).
➢ 4. View Updates:
o The Controller updates the View to reflect the changes in the Model
(e.g., updating the cart UI with the new item).
➢ Advantages of MVC:
➢ Separation of Concerns:
o Keeps the business logic (Model), UI (View), and control flow
(Controller) separate, making it easier to modify or replace one part
without affecting others.
➢ Code Reusability:
o The Model and View components can be reused across different
projects, reducing redundant code.
➢ Easier Maintenance:
o Changes in one component (e.g., UI changes in the View) don’t require
changes in the other components (Model and Controller).
➢ Testability:
o Testing is easier because each component has a distinct responsibility.
Unit tests can be written for the Model and Controller separately.
➢ Collaboration:
o Designers can focus on the View, while developers can focus on the
Model and Controller, allowing for better collaboration between teams.
➢ The MVC design pattern is fundamental in iOS development, helping to
structure an app in a clean and maintainable way. It simplifies the
development process by dividing responsibilities into Model, View, and
Controller, making code easier to manage, test, and scale.
Other Answer:
➢ MVC stands for Model-View-Controller, which is a design pattern used in
software development, including iOS applications. It helps organize code by
separating the business logic, user interface, and control flow, making
applications more modular, maintainable, and scalable.
➢ Components of MVC
➢ 1. Model (Data & Business Logic)
117
o Represents the data and business logic of the application.
o Manages data retrieval, storage, and processing.
o Does not directly interact with the user interface.
o Example: A User model that stores user information and handles
validation.
➢ 2. View (User Interface)
o Handles UI elements such as labels, buttons, and tables.
o Displays data from the Model but does not handle logic.
o Updates when the Controller instructs it to.
o Example: A UIViewController that displays user details.
➢ 3. Controller (Mediator between Model & View)
o Acts as a bridge between the Model and the View.
o Handles user interactions and updates the Model or View accordingly.
o Example: A UserViewController that fetches user data and updates the
UI.
➢ How MVC Works in iOS?
o User interacts with the View (e.g., taps a button).
o Controller receives the event and processes it.
o Controller updates the Model based on the event.
o Model changes data and notifies the Controller.
o Controller updates the View to reflect the new data.
➢ Example of MVC in iOS (Swift Code)
// Model
class User {
var name: String
var age: Int
118
var user: User?
119
o Manages touch inputs, motion events, and gestures (tap, swipe, pinch,
etc.).
o Supports multi-touch functionality.
➢ Graphics & Animation
o Includes frameworks like Core Graphics, Core Animation, and Metal for
high-quality rendering.
o Provides built-in animations for smooth transitions.
➢ Data Management
o Uses Core Data for local storage and database management.
o Supports UserDefaults, FileManager, and CloudKit for data persistence.
➢ Multimedia & Audio
o Supports AVFoundation and Core Audio for playing and recording
audio/video.
o Allows media processing, camera access, and live streaming.
➢ Networking & Connectivity
o Provides NSURLSession for API communication.
o Supports push notifications and background downloading.
➢ Location & Sensors
o Uses Core Location for GPS and location-based services.
o Accesses device sensors like accelerometer, gyroscope, and proximity
sensor.
➢ Multitasking & Background Execution
o Supports running apps in the background for tasks like downloading
and location tracking.
➢ Cocoa Touch Architecture
o Cocoa Touch is part of the iOS architecture, which consists of the
following layers:
▪ 1. Cocoa Touch (Top Layer) – Provides UI frameworks and event
handling.
▪ 2. Media Layer – Handles graphics, animations, and audio/video.
▪ 3. Core Services – Includes data management, networking, and
system services.
▪ 4. Core OS (Bottom Layer) – Manages security, low-level
networking, and device communication.
➢ Why is Cocoa Touch Important?
o It simplifies UI design and user interactions.
o Provides ready-to-use APIs and frameworks for faster development.
o Ensures smooth performance and efficient memory management.
o Supports cross-device development for iPhone, iPad, Apple Watch, and
Apple TV.
120
➢ Cocoa Touch is the foundation of iOS app development, offering a set of
frameworks for UI, data handling, multimedia, and networking. It plays a
crucial role in creating responsive, interactive, and high-performance
applications for Apple devices.
import UIKit
// Create a UITextView
121
let textView = UITextView(frame: CGRect(x: 20, y: 100, width: 300, height:
150))
// Set properties
textView.text = "This is a sample UITextView. You can enter multiple lines
of text here."
textView.font = UIFont.systemFont(ofSize: 16)
textView.textColor = UIColor.black
textView.backgroundColor = UIColor.lightGray
textView.isEditable = true // Enable editing
textView.isScrollEnabled = true // Enable scrolling
➢ UITextView is a powerful text control used for multi-line text input and display
in iOS apps. It is highly customizable and supports scrolling, formatting, and
user interaction, making it essential for text-heavy applications like chat apps,
notes, and forms.
class User {
var name: String
var age: Int
122
self.name = name
self.age = age
}
}
o Here, User is the Model that stores data.
➢ 2. View (User Interface - UI Layer)
o Handles the visual representation of data.
o Displays information but does not handle logic.
o Updates when the Controller instructs it to.
o Example:
import UIKit
class UserController {
func getUserData() -> User {
return User(name: "John Doe", age: 25) // Fetch user data
}
}
o This Controller retrieves the Model's data and passes it to the View.
➢ How MVC Works in iOS?
o User interacts with the View (e.g., taps a button).
123
o Controller receives the event and processes it.
o Controller updates the Model based on the event.
o Model changes data and notifies the Controller.
o Contr oller updates the View to reflect the new data.
➢ Example Flow in iOS App:
o The ViewController (Controller) fetches data from the Model.
o The data is displayed in the View.
o If a user updates the data, the Controller sends the changes to the
Model.
o The updated Model data is then reflected in the View.
➢ Full Example: MVC in iOS (Swift Code)
import UIKit
// MODEL
class User {
var name: String
var age: Int
// CONTROLLER
class UserController {
func getUserData() -> User {
return User(name: "John Doe", age: 25)
}
}
// VIEW + CONTROLLER
class UserViewController: UIViewController {
124
let user = userController.getUserData() // Fetch user data
nameLabel.text = user.name // Update UI
}
}
➢ MVC is a fundamental architectural pattern in iOS development. It helps in
creating well-structured, maintainable, and scalable apps by separating the
Model (data), View (UI), and Controller (logic). Apple recommends using MVC
for better app organization and efficiency.
myButton.frame = CGRect(x: 50, y: 50, width: 150, height: 50) // Set size and
position
➢ Step 3: Add Action to the Button
o Define an action that gets triggered when the button is tapped.
125
@objc func buttonTapped() {
print("Button Clicked!")
// Configure Container
containerView.frame = CGRect(x: 20, y: 100, width: 300, height: 200)
containerView.backgroundColor = UIColor.lightGray
view.addSubview(containerView)
// Create Button
let myButton = UIButton(type: .system)
myButton.setTitle("Click Me", for: .normal)
myButton.backgroundColor = UIColor.systemBlue
myButton.setTitleColor(UIColor.white, for: .normal)
myButton.layer.cornerRadius = 10
myButton.frame = CGRect(x: 50, y: 50, width: 150, height: 50)
// Add Action
myButton.addTarget(self, action: #selector(buttonTapped), for:
.touchUpInside)
126
}
}
127
o Developers must use different frameworks for cross-platform
development.
➢ 2. Steep Learning Curve
o Requires knowledge of Swift or Objective-C, which can be difficult for
beginners.
o Some frameworks (like Core Data) have complex implementations.
➢ 3. Restrictions and App Store Guidelines
o Apple imposes strict rules and guidelines for publishing apps on the
App Store.
o Developers need to follow strict security and privacy policies, which can
limit flexibility.
➢ 4. High Dependence on Apple Updates
o Any changes in Apple's APIs or frameworks require developers to
update their apps frequently.
o Older apps may break with major iOS updates.
➢ 5. Limited Open-Source Libraries
o Unlike Android (which has a vast open-source community), Cocoa
Touch relies heavily on Apple-provided frameworks.
o Fewer third-party open-source libraries compared to Android
development.
➢ In the summary, Cocoa Touch is a powerful framework for iOS development,
offering rich UI components, gesture support, efficient memory management,
and deep integration with Apple technologies. However, it has some
limitations, such as being restricted to Apple platforms, a steep learning curve,
and dependence on Apple’s ecosystem. Despite these drawbacks, Cocoa
Touch remains the best choice for developing high-quality iOS applications.
128
o Manages touch events, gestures, and animations.
➢ 2. Gesture and Event Handling
o Supports multi-touch gestures (tap, swipe, pinch, rotate).
o Handles UI interactions smoothly.
➢ 3. Graphics and Animation
o Uses Core Graphics, Core Animation, Metal for rendering graphics.
o Enables smooth animations and transitions.
➢ 4. Multimedia and Camera Support
o Frameworks like AVFoundation and Core Media allow media playback
and recording.
o Supports live video streaming and camera integration.
➢ 5. Data Management and Persistence
o Uses Core Data and UserDefaults for storing app data.
o Supports CloudKit for cloud-based data storage.
➢ 6. Networking and Web Support
o Provides NSURLSession for API communication.
o Supports background downloads, push notifications, and web views.
➢ 7. Location and Sensor Support
o Uses Core Location for GPS-based tracking.
o Accesses sensors like accelerometer, gyroscope, and proximity sensor.
➢ Cocoa Touch Architecture in iOS
➢ Cocoa Touch is part of the iOS Architecture, which consists of four layers:
➢ 1. Cocoa Touch Layer (Top Layer)
o Provides UI frameworks and event handling.
o Includes UIKit, EventKit, AddressBook, Core Motion.
➢ 2. Media Layer
o Handles graphics, animations, and audio/video.
o Includes Core Graphics, Core Animation, AVFoundation, and Metal.
➢ 3. Core Services Layer
o Provides system services like database management and networking.
o Includes Core Data, CloudKit, Foundation, and Networking APIs.
➢ 4. Core OS Layer (Bottom Layer)
o Manages low-level functions like security and file system access.
o Includes XNU Kernel, Bluetooth, and Security Frameworks.
➢ Advantages of Using Cocoa Touch
o Pre-built UI Components – Saves development time.
o Supports Multi-Touch and Gesture Handling – Improves user
experience.
o Efficient Memory Management – Uses ARC (Automatic Reference
Counting).
129
o Seamless Integration with Apple Ecosystem – Works with iCloud, Apple
Pay, and SiriKit.
o Powerful Graphics and Media Capabilities – Uses Metal, Core
Animation, and AVFoundation.
➢ Disadvantages of Cocoa Touch
o Limited to Apple Devices – Cannot be used for Android or other
platforms.
o Learning Curve – Requires knowledge of Swift or Objective-C.
o Frequent Updates – Developers need to update apps for every iOS
version.
o Strict App Store Policies – Apps must follow Apple's guidelines for
approval.
➢ Example of Cocoa Touch in iOS App Development (Swift Code)
➢ Creating a Simple UIButton Using UIKit (Cocoa Touch)
import UIKit
// Create a UIButton
let myButton = UIButton(type: .system)
myButton.setTitle("Tap Me", for: .normal)
myButton.backgroundColor = UIColor.systemBlue
myButton.setTitleColor(UIColor.white, for: .normal)
myButton.frame = CGRect(x: 100, y: 200, width: 150, height: 50)
// Add action
myButton.addTarget(self, action: #selector(buttonTapped), for:
.touchUpInside)
130
}
131
o Provides tools for app signing, validation, and submission to the App
Store.
o Supports TestFlight for beta testing apps before release.
➢ How Xcode Helps in App Development
o Speeds up development with built-in tools and templates.
o Enhances UI design through Interface Builder and Storyboards.
o Enables efficient testing using the iOS simulator.
o Improves code quality with debugging and performance analysis tools.
o Simplifies app deployment with App Store integration.
➢ Xcode is an all-in-one development environment that simplifies the process of
building, testing, and deploying iOS and macOS applications. With its
powerful editor, UI designer, debugging tools, and simulator, Xcode is
essential for efficient and professional app development.
132
o Provides tools for app signing, validation, and submission to the App
Store.
o Supports TestFlight for beta testing apps before release.
➢ Uses of Xcode
o Developing iOS, macOS, watchOS, and tvOS applications.
o Designing UI using Storyboards and Interface Builder.
o Testing and debugging apps with the iOS Simulator.
o Optimizing app performance using Instruments tool.
o Collaborating with teams using Git version control.
o Deploying apps to the App Store with built-in distribution tools.
➢ Xcode is a powerful and essential tool for developing Apple platform
applications. With features like a code editor, UI designer, simulator, and
debugging tools, it helps developers create, test, and deploy apps efficiently.
5. List various visual control in IOS. Explain any one with example.
➢ In iOS development, visual controls are elements that allow users to interact
with the app’s interface. These controls are part of the UIKit framework and
can be used to display content, gather user input, or create interactive UI
elements.
➢ Common Visual Controls in iOS
o UILabel – Displays static text.
o UIButton – A clickable button to trigger actions.
o UITextField – A single-line text input field.
o UITextView – A multi-line text input field.
o UIImageView – Displays an image.
o UISwitch – A toggle switch for on/off states.
o UISlider – Allows the user to select a value from a range.
o UISegmentedControl – A horizontal control with multiple segments.
o UIProgressView – Displays progress for tasks (like downloading).
o UITableView – Displays a scrollable list of data in rows.
o UICollectionView – Displays a grid or collection of items.
o UIActivityIndicatorView – A spinner to show activity or loading state.
o UIPageControl – Indicates the current page in a scrollable list of pages.
o UIAlertController – Used for presenting alerts and action sheets.
o UIDatePicker – Allows users to select dates and times.
➢ Explaining One Visual Control: UIButton
➢ UIButton
133
o UIButton is a visual control used to create clickable buttons in iOS apps.
Buttons are used to trigger actions, navigate to other views, or submit
data.
o Key Features of UIButton:
o Customizable text, images, and background color.
o Supports different states like normal, highlighted, and disabled.
o Can trigger actions like tapping and long-pressing.
o Can have custom animations when clicked.
➢ Example of UIButton in Swift
import UIKit
134
➢ Explanation of the Example:
➢ Creating the UIButton:
o A UIButton is created with .system type. You can change the button
type as needed (e.g., .custom for custom buttons).
➢ Setting the Title and Style:
o The title "Click Me" is set for the button in its normal state. The
background color is set to blue, and the title color is set to white.
➢ Adding an Action:
o The addTarget method connects the button with the buttonTapped
function. The action is triggered when the user taps the button.
➢ Displaying the Button:
o The button is added to the view hierarchy using
self.view.addSubview(button).
➢ UIButton is a versatile and essential visual control in iOS development. It can
be customized and used to trigger various actions, making it an important
element for user interaction in iOS apps.
135
➢ Code Implementation:
import UIKit
// Declare fields
var contacts = [(name: String, phone: String)]() // Array to store contacts
// Insert contact
@IBAction func insertContact(_ sender: UIButton) {
guard let name = nameTextField.text, !name.isEmpty,
let phone = phoneTextField.text, !phone.isEmpty else {
showAlert(message: "Please enter both name and phone number")
return
}
contacts.append((name: name, phone: phone))
tableView.reloadData()
clearFields()
}
// Update contact
@IBAction func updateContact(_ sender: UIButton) {
guard let name = nameTextField.text, !name.isEmpty,
let phone = phoneTextField.text, !phone.isEmpty else {
showAlert(message: "Please enter both name and phone number")
return
}
136
if let selectedIndexPath = tableView.indexPathForSelectedRow {
contacts[selectedIndexPath.row] = (name: name, phone: phone)
tableView.reloadData()
clearFields()
} else {
showAlert(message: "Please select a contact to update")
}
}
// Delete contact
@IBAction func deleteContact(_ sender: UIButton) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
contacts.remove(at: selectedIndexPath.row)
tableView.reloadData()
clearFields()
} else {
showAlert(message: "Please select a contact to delete")
}
}
137
}
➢ Storyboard Design:
o UITextField for name input (place it on top).
o UITextField for phone number input (below the name input).
o UIButton for each action (insert, update, delete, and exit).
o UITableView to display the list of contacts.
o Set the identifier for table cells as "ContactCell".
o Connect the IBOutlet and IBAction in the code with the UI elements.
➢ Explanation of the Code:
➢ Data Structure:
o An array contacts is used to store the contact entries, where each
contact is a tuple with name and phone.
➢ Insert Contact:
o The insertContact method adds a new contact to the contacts array if
both the name and phone number are provided.
o The UITableView is reloaded to display the updated list.
➢ Update Contact:
o The updateContact method allows updating a contact if a row is
selected in the UITableView. The existing data at the selected index is
replaced with the new values.
➢ Delete Contact:
o The deleteContact method removes the selected contact from the
contacts array.
➢ Exit:
138
o The exitApp method uses the exit(0) function to close the app.
➢ UITableView:
o Implements the necessary data source methods to display the contacts
in the table view. The numberOfRowsInSection method returns the
number of contacts, and the cellForRowAt method configures each cell
with the contact's name and phone number.
➢ In the summary, This iOS application demonstrates basic CRUD (Create, Read,
Update, Delete) operations using UITextField, UIButton, and UITableView. The
app allows users to insert, update, delete, and view contacts, with an exit
option to close the app. You can expand this project to include persistent
storage (e.g., CoreData or UserDefaults) to save the contacts between app
sessions.
139