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

Android Studio SQLite

The document provides a comprehensive overview of the Android Activity Lifecycle and SQLite Database management. It details the six key callbacks of the Activity Lifecycle (onCreate, onStart, onResume, onPause, onStop, onDestroy) and their functions in managing activity states. Additionally, it explains the SQLiteOpenHelper class, its methods for database creation and management, and the use of ContentValues for database operations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Android Studio SQLite

The document provides a comprehensive overview of the Android Activity Lifecycle and SQLite Database management. It details the six key callbacks of the Activity Lifecycle (onCreate, onStart, onResume, onPause, onStop, onDestroy) and their functions in managing activity states. Additionally, it explains the SQLiteOpenHelper class, its methods for database creation and management, and the use of ContentValues for database operations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Mobile Application Development (MAD)

Comprehensive Question & Answer Bank


Unit 6: SQLite Database | Activity Lifecycle | CS Unit 4: Programming for Different Devices
Prepared from course notes of Prof. Shagufta Khan
BONUS: Android Activity Lifecycle

Overview
To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of
six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). The system
invokes each of these callbacks as an activity enters a new state.
Lifecycle Flow (Text Diagram):
Activity Launched

onCreate() ← Called once when activity is first created

onStart() ← Activity becomes visible

onResume() ← Activity in foreground, interactive

[Activity Running]
↓ (Another activity / phone call / screen off)
onPause() ← Activity partially obscured
↓ (Activity fully hidden)
onStop() ← Activity no longer visible
↓ (User returns) ↓ (Finishing)
onRestart() onDestroy()
↓ ↓
onStart() Activity Shut Down

Detailed Explanation of Each Callback


1. onCreate()
The onCreate() method is invoked when an activity is first created, placing it in the Created state. It
initializes the activity with startup logic that should only occur once. The method receives a
savedInstanceState Bundle which holds the activity's previous state if it was saved before; otherwise it
is null. This is where you call setContentView() to inflate the layout and initialize UI elements using
findViewById().
2. onStart()
After onCreate() completes, the activity moves to the Started state and onStart() is called. This makes
the activity visible to the user and prepares it to enter the foreground and become interactive. This is
where the app initializes code that maintains the UI.
3. onResume()
In the Resumed state, the app is in the foreground and interacts with the user. The app stays in this
state until something happens to take focus away — such as receiving a phone call, navigating to
another activity, or the device screen turning off. This is the active running state.
4. onPause()
When an interruptive event occurs, the activity enters the Paused state, triggering onPause(). The
activity is no longer in the foreground (though it may still be visible in multi-window mode). Use
onPause() to pause operations that should not continue while paused (e.g., pausing a video, releasing
camera). Implement onResume() to reinitialize components released in onPause().
5. onStop()
When the activity is no longer visible to the user, it enters the Stopped state and onStop() is invoked.
This happens when another activity covers the screen or the activity is about to be terminated. In
onStop(), release or adjust resources not needed while the app is invisible (e.g., pausing animations,
switching to coarse location updates).
6. onDestroy()
From the Stopped state, an activity either resumes via onRestart() → onStart(), or is permanently
finished and destroyed via onDestroy(). onDestroy() is called when the activity is completely dismissed
by the user, finish() is called, or the system temporarily destroys it due to configuration changes like
device rotation.
Callback State Activity Visible? Primary Use
onCreate() Created No Initialize UI, set layout,
bind data
onStart() Started Yes (becoming visible) Start UI-related work
onResume() Resumed Yes (foreground) Start animations, open
camera, resume
onPause() Paused Partially Pause animations,
release camera
onStop() Stopped No Release heavy resources,
save data
onDestroy() Destroyed No Final cleanup, release all
resources
UNIT 6: Preserving and Saving Data in Local Database (SQLite)

SHORT ANSWER QUESTIONS (2 Marks Each)


Q1 & Q9. What is SQLite?
SQLite is an embedded, lightweight relational database management system (RDBMS) that operates
as a library within applications rather than as a standalone server. Written in C, SQLite is open-source
and is widely used in mobile and embedded systems due to its small size and ease of use. In Android,
it is managed via a Java-based API provided by the Android SDK. A SQLite database is just a file
stored on the device — when not in use, it consumes no processor time, which is important for
preserving battery life. SQLite supports standard SQL commands including CREATE, INSERT,
SELECT, UPDATE, and DELETE.

Q2. What is SQLiteOpenHelper class?


SQLiteOpenHelper is a base class in Android that simplifies the creation and management of SQLite
databases. It provides built-in methods for creating, opening, upgrading, and closing databases. To use
it, developers create a subclass that overrides two mandatory callback methods: onCreate() (called
when the database is created for the first time) and onUpgrade() (called when the database version
needs to be updated). It abstracts away the complexity of directly managing database files.

Q3. What is the purpose of the onCreate() method in SQLiteOpenHelper?


The onCreate(SQLiteDatabase db) method in SQLiteOpenHelper is called when the database is
created for the first time (i.e., when no database file exists). It is the ideal location to initialize the
database schema — creating tables using execSQL() and inserting any initial seed data. This method
is called only once per database lifetime unless the database is deleted and recreated.

Q4. What is the purpose of the onUpgrade() method?


The onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) method is called when the
database version number in the code is higher than the version stored on the device. It is used when an
application update requires changes to the database schema — such as adding new columns, creating
new tables, or modifying existing ones. Typically, the old table is dropped and recreated, or ALTER
TABLE commands are used to modify the schema without data loss.

Q5. What is the execSQL() method?


execSQL(String sql) is a method of the SQLiteDatabase class that executes a single SQL statement
that does not return any data. It is used for DDL (Data Definition Language) operations like CREATE
TABLE and DROP TABLE, and DML operations like INSERT, UPDATE, DELETE when return values
(such as row IDs or affected row counts) are not needed. It can use bind arguments (bindArgs) to
protect against SQL injection attacks.

Q6. What is the rawQuery() method?


rawQuery(String sql, String[] selectionArgs) is a method of SQLiteDatabase used to execute raw SQL
SELECT queries that return a result set. It returns a Cursor object, which is used to iterate through the
rows of the result set and retrieve data column by column. It accepts selection arguments as a String
array to safely substitute '?' placeholders in the SQL statement, preventing SQL injection. It should only
be used for SELECT statements, not for INSERT/UPDATE/DELETE.

Q7. What methods are used for insert, update, and delete operations?
The three convenience methods of SQLiteDatabase for DML operations are:
• insert(String table, String nullColumnHack, ContentValues values) – Inserts a new row. Returns
the row ID of the inserted row, or -1 if an error occurred.
• update(String table, ContentValues values, String whereClause, String[] whereArgs) – Modifies
existing rows matching the WHERE clause. Returns the number of rows affected.
• delete(String table, String whereClause, String[] whereArgs) – Removes rows matching the
WHERE clause. Returns the number of rows deleted.

Q8. What are ContentValues in SQLite?


ContentValues is a key-value data structure (similar to a Map) used in Android SQLite operations to
store column name-value pairs for insert and update operations. The key is the column name (String)
and the value is the data to insert or update for that column. Using ContentValues builds the SQL query
internally and provides protection against SQL injection. Example: ContentValues cv = new
ContentValues(); [Link]('name', 'Ahmed'); [Link]('age', 22);

Q10. List various SQLite Methods.


The key methods available on the SQLiteDatabase class in Android are:
• execSQL(String sql) – Executes any SQL statement that returns no data (CREATE, DROP,
INSERT, UPDATE, DELETE).
• rawQuery(String sql, String[] args) – Executes a SELECT query and returns a Cursor object.
• insert(table, nullColumnHack, ContentValues) – Convenience method for inserting a row.
• update(table, ContentValues, whereClause, whereArgs) – Convenience method for updating
rows.
• delete(table, whereClause, whereArgs) – Convenience method for deleting rows.
• query(table, columns, selection, selectionArgs, groupBy, having, orderBy) – Structured SELECT
query.
• getWritableDatabase() – Opens/creates a database for read-write access.
• getReadableDatabase() – Opens/creates a database for read-only access.
• close() – Closes the database connection.

Q11. How does rawQuery() differ from execSQL() in SQLite?


Aspect rawQuery() execSQL()
Purpose Execute SQL SELECT queries that Execute SQL statements that do
return data not return data
Returns A Cursor object to navigate the void (no return value)
result set
SQL Type Read-only (SELECT only) Write/modify (INSERT, UPDATE,
DELETE, CREATE, DROP)
Use Case Fetching rows from a table Modifying database structure or
data
Example [Link]("SELECT * FROM [Link]("CREATE TABLE
students", null) students (...)")

Q12. How does the delete method work in SQLite?


The delete(String table, String whereClause, String[] whereArgs) method removes rows from a
specified table. The whereClause is an optional SQL WHERE condition (without the WHERE keyword)
that specifies which rows to delete. The whereArgs array provides values to substitute for '?'
placeholders in the whereClause, protecting against SQL injection. It returns the number of rows
deleted. If whereClause is null, all rows in the table are deleted. Example: [Link]('students', 'id=?',
new String[]{'1'}); deletes the student with id = 1.
Q13. What is the role of the onCreate method in SQLiteOpenHelper?
The onCreate(SQLiteDatabase db) method in SQLiteOpenHelper is the first method called when the
database is created for the very first time. Its role is to set up the initial database schema — typically by
executing CREATE TABLE SQL statements using [Link](). It may also insert default or seed
data. This method runs only once during the lifetime of the database file. If the database already exists
on the device, onCreate() is skipped and onUpgrade() may be called instead if the version number has
changed.

Q14. State the usage of ContentValues in SQLite.


ContentValues is a class used in Android SQLite operations to hold a set of values that can be used by
the insert() and update() methods of SQLiteDatabase. Its key usages are:
• For INSERT operations: ContentValues stores the column name-value pairs for the new row to
be inserted.
• For UPDATE operations: ContentValues stores the column names and their new values that
should be updated in matching rows.
• It provides protection against SQL injection because values are passed separately from the
SQL structure rather than being embedded directly in SQL strings.
• Example: ContentValues cv = new ContentValues(); [Link]('name', 'Sara'); [Link]('age', 21);
[Link]('students', null, cv);

LONG ANSWER QUESTIONS (10 Marks Each)


Q1. Explain SQLite database in Android.
Introduction to SQLite
SQLite is an embedded, lightweight, open-source relational database management system (RDBMS)
that operates as a library within applications rather than as a standalone server process. Written in C,
SQLite handles all database operations internally, making it ideal for use in mobile and embedded
systems where resources are constrained.
Key Characteristics of SQLite in Android:
• Self-contained: SQLite is integrated directly into the application as a library. There is no
separate server process to install or manage.
• Zero-configuration: No setup or administration is required. The database is just a file on the
filesystem.
• Serverless: Unlike MySQL or PostgreSQL, SQLite does not require a separate server process
or network communication.
• Lightweight and efficient: A SQLite database is simply a file stored on disk. When not in use, it
consumes no processor time — critical for preserving battery life on mobile devices.
• Full SQL support: SQLite supports most of the standard SQL commands including CREATE,
INSERT, SELECT, UPDATE, and DELETE.
Storage Location of SQLite Database in Android:
Android automatically creates a folder for each app where the database file is stored. The path follows
this pattern:
/data/data/<package-name>/databases/<database-filename>.db
For example, for a package [Link] with database [Link]:
/data/data/[Link]/databases/[Link]
Each database consists of two files: (1) The main database file containing all data, and (2) A journal file
(e.g., [Link]-journal) that records recent changes. If something goes wrong, Android uses the
journal file to roll back (undo) the latest changes.
SQLite Storage Classes (Data Types):
Storage Class Description
NULL Stores a null value.
INTEGER Signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes
depending on the magnitude of the value.
REAL A floating-point value stored as an 8-byte IEEE floating-
point number.
TEXT A text string stored using database encoding (UTF-8,
UTF-16BE, or UTF-16LE).
BLOB Binary data stored exactly as it was input (e.g., images,
files).

Why SQLite for Android?


• No separate installation needed — built into every Android device.
• Ideal for storing structured data locally — contacts, notes, messages.
• Efficient use of storage and memory on resource-constrained mobile devices.
• Standard SQL interface — familiar to developers.
• Persistent storage — data survives app restarts and device reboots.
Q2. Explain SQLiteOpenHelper class in detail.
The SQLiteOpenHelper class is a base class in Android that simplifies the management of SQLite
databases. Instead of manually handling database file creation, version management, and upgrades,
developers extend SQLiteOpenHelper and override its key callback methods.
How to Use SQLiteOpenHelper:
Create a subclass (commonly called DBHelper or DatabaseHelper) that extends SQLiteOpenHelper
and overrides the two mandatory methods: onCreate() and onUpgrade().
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "[Link]";
public static final String TABLE_NAME = "students";
public static final int DB_VERSION = 1;

public DBHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
[Link]("CREATE TABLE students " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, age INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
[Link]("DROP TABLE IF EXISTS students");
onCreate(db);
}
}
Key Methods of SQLiteOpenHelper:
1. onCreate(SQLiteDatabase db)
• Called when the database is first created (i.e., the database file does not yet exist on the
device).
• Used to create tables and insert initial seed data.
• Receives the SQLiteDatabase object db which is used to execute SQL via [Link]().
• Called only ONCE in the lifetime of the database file.
2. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
• Called when the version number passed to the SQLiteOpenHelper constructor is higher than the
version stored in the existing database file.
• Used to migrate the database schema — add new columns, create new tables, or restructure
existing ones.
• Receives three parameters: the database object, the old version number, and the new version
number.
• Typically implemented by dropping old tables and calling onCreate() to recreate them (data
loss) or using ALTER TABLE to preserve existing data.
3. getWritableDatabase()
• Opens or creates a database for both reading and writing.
• Returns a SQLiteDatabase object that allows INSERT, UPDATE, DELETE, and SELECT
operations.
• Triggers onCreate() if the database does not exist, or onUpgrade() if the version has changed.
4. getReadableDatabase()
• Opens or creates a database for reading only.
• Returns a SQLiteDatabase object that allows only SELECT operations.
• Falls back to getWritableDatabase() if no read-only mode is available.
5. close()
• Closes the database connection and releases associated resources.
• Should be called when the database is no longer needed to free memory.
How SQLiteOpenHelper Makes Decisions:
• If the database does NOT exist: Creates the database file and calls onCreate().
• If the database EXISTS and the version MATCHES: No method is called — database is up to
date.
• If the database EXISTS and the helper version is HIGHER: Calls onUpgrade() to upgrade the
schema.
• If the database EXISTS and the helper version is LOWER: Calls onDowngrade() (if overridden).
Q3. Explain various SQLite methods: execSQL, rawQuery, insert, update, delete.
In Android SQLite development, the SQLiteDatabase class provides several methods for interacting
with the database. The methods execSQL() and rawQuery() are general-purpose, while insert(),
update(), and delete() are convenience methods that abstract common DML operations.
1. execSQL(String sql)
Executes a single SQL statement that does NOT return any data. It is used for DDL (Data Definition
Language) statements like CREATE TABLE, DROP TABLE, and DML statements (INSERT, UPDATE,
DELETE) when return values are not needed. Supports bind arguments to prevent SQL injection.
// Create a table
[Link]("CREATE TABLE students " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");

// Drop a table
[Link]("DROP TABLE IF EXISTS students");
2. rawQuery(String sql, String[] selectionArgs)
Executes a raw SQL SELECT query and returns a Cursor object to navigate through the result rows.
The '?' placeholders in the SQL are safely replaced by values in the selectionArgs array. Should NOT
be used for INSERT, UPDATE, or DELETE.
Cursor cursor = [Link](
"SELECT * FROM students WHERE age > ?",
new String[]{"18"});

if ([Link]()) {
do {
String name = [Link]([Link]("name"));
int age = [Link]([Link]("age"));
} while ([Link]());
}
[Link]();
3. insert(String table, String nullColumnHack, ContentValues values)
A convenience method for inserting a single new row into a table. Uses a ContentValues object (key-
value map of column names to values). Returns the row ID of the newly inserted row, or -1 if an error
occurred. The nullColumnHack parameter handles the edge case of inserting a completely empty row
— pass null if not needed.
ContentValues values = new ContentValues();
[Link]("name", "Ahmed");
[Link]("age", 22);
long rowId = [Link]("students", null, values);
4. update(String table, ContentValues values, String whereClause, String[] whereArgs)
A convenience method for modifying existing rows in a table. Uses ContentValues to specify the
columns and their new values. The whereClause and whereArgs specify which rows to update (similar
to a SQL WHERE clause). Returns the number of rows affected by the update.
ContentValues values = new ContentValues();
[Link]("age", 23); // Update age to 23
int rowsAffected = [Link](
"students",
values,
"name = ?",
new String[]{"Ahmed"});
5. delete(String table, String whereClause, String[] whereArgs)
A convenience method for deleting rows from a table. Uses a whereClause and whereArgs to
determine which rows to delete. Does not require a ContentValues object. Returns the number of rows
deleted. If whereClause is null, all rows in the table are deleted.
int rowsDeleted = [Link](
"students",
"id = ?",
new String[]{"1"}); // Delete student with id = 1
Summary Comparison Table:
Method Purpose SQL Type Returns Best For
execSQL() Execute raw SQL DDL, DML void CREATE, DROP,
(no result) DDL statements
rawQuery() Execute raw SELECT only Cursor Custom SELECT
SELECT query queries
insert() Insert a new row INSERT long (row ID) Adding new records
update() Modify existing rows UPDATE int (rows affected) Updating records
with WHERE
delete() Remove rows DELETE int (rows affected) Deleting records
with WHERE
Q4. Explain CRUD operations in SQLite with suitable code examples.
CRUD stands for Create, Read, Update, and Delete — the four fundamental operations for persistent
data management in any database system. In Android SQLite, these operations are performed using
the SQLiteDatabase class methods.
Setup: DBHelper Class
public class DBHelper extends SQLiteOpenHelper {
static final String DB_NAME = "[Link]";
static final String TABLE = "students";
static final int VERSION = 1;

public DBHelper(Context ctx) {


super(ctx, DB_NAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
[Link]("CREATE TABLE students (id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " name TEXT, age INTEGER, grade TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int old, int nw) {
[Link]("DROP TABLE IF EXISTS students");
onCreate(db);
}
}
C — CREATE (Insert)
The INSERT operation adds a new record to the database. Use the insert() convenience method with
ContentValues, or execSQL() for raw SQL.
// Using insert() method (preferred)
SQLiteDatabase db = [Link]();
ContentValues values = new ContentValues();
[Link]("name", "Ahmed");
[Link]("age", 20);
[Link]("grade", "A");
long newRowId = [Link]("students", null, values);
if (newRowId == -1) { /* Error occurred */ }
[Link]();
R — READ (Select / Query)
The SELECT operation retrieves data. Use rawQuery() for custom queries or the query() method for
structured queries. The result is accessed through a Cursor object.
// Using rawQuery() — retrieve all students
SQLiteDatabase db = [Link]();
Cursor cursor = [Link]("SELECT * FROM students", null);

List<String> result = new ArrayList<>();


if ([Link]()) {
do {
int id = [Link]([Link]("id"));
String name = [Link]([Link]("name"));
int age = [Link]([Link]("age"));
[Link](id + " | " + name + " | " + age);
} while ([Link]());
}
[Link]();
[Link]();
U — UPDATE (Modify)
The UPDATE operation modifies existing records. Use the update() convenience method with
ContentValues and a WHERE clause to target specific rows.
// Update grade of student named 'Ahmed' to 'A+'
SQLiteDatabase db = [Link]();
ContentValues values = new ContentValues();
[Link]("grade", "A+");
int rowsUpdated = [Link](
"students",
values,
"name = ?",
new String[]{"Ahmed"}),
[Link]();
D — DELETE (Remove)
The DELETE operation removes records from the database. Use the delete() convenience method with
a WHERE clause to target specific rows.
// Delete student with id = 1
SQLiteDatabase db = [Link]();
int rowsDeleted = [Link](
"students",
"id = ?",
new String[]{"1"});
[Link]();
Using CRUD from Activity:
DBHelper dbHelper = new DBHelper(this);
// CREATE
ContentValues cv = new ContentValues();
[Link]("name", "Sara"); [Link]("age", 21); [Link]("grade", "B");
[Link]().insert("students", null, cv);

// READ
Cursor c = [Link]().rawQuery("SELECT * FROM students", null);

// UPDATE
ContentValues cv2 = new ContentValues();
[Link]("grade", "A");
[Link]().update("students", cv2, "name=?", new String[]
{"Sara"});

// DELETE
[Link]().delete("students", "name=?", new String[]{"Sara"});
CS UNIT 4: Programming for Different Devices

LONG ANSWER QUESTIONS (10 Marks Each)


Q1. Explain the concept of Screen Compatibility in Android.
Overview
Android devices vary widely in screen sizes and pixel densities, which affects how apps appear across
different devices. The Android system performs basic scaling to adapt the user interface to various
screens, but developers need to implement specific strategies for optimal performance and
appearance. Screen compatibility refers to the set of practices and tools Android provides to ensure
apps look and function correctly on all devices — from small phones to large tablets, TVs, and
foldables.
Key Aspects of Screen Compatibility:
1. Screen Sizes
Android devices come in various screen sizes and the visible space for an app's UI can vary due to
factors like screen orientation (portrait/landscape) or multi-window mode. Developers should design
layouts that adapt to available screen space.
• Example: A tablet has more screen space than a phone, so a dual-pane layout is appropriate —
with a list on the left and details on the right. On a phone, the list and details might be shown in
separate activities.
2. Flexible Layouts
Design UI to be flexible so it adapts to different screen sizes. Avoid hardcoded dimensions and pixel
values. Use relative positioning and flexible sizing instead.
• Example: Instead of setting a button width to a fixed 100 pixels, use
layout_width='wrap_content' or layout_width='match_parent' to allow the button to adjust based
on the screen.
• Use ConstraintLayout or LinearLayout with weights for adaptive positioning.
3. Alternative Layouts
Create different layout XML files for different screen sizes to optimize the user experience. Android
uses resource qualifiers to automatically select the correct layout.
• layout/ — default layouts for phones.
• layout-large/ — layouts for tablets (>7 inch).
• layout-xlarge/ — layouts for very large screens (>10 inch).
• layout-land/ — layouts for landscape orientation.
• Android automatically chooses the appropriate layout based on the device's screen
configuration at runtime.
4. Stretchable Images (Nine-Patch)
A Nine-Patch image is a special PNG image format (.[Link]) used in Android that allows specific areas
of an image to stretch while other areas remain unchanged. This technique prevents distortion when UI
components resize.
• Normal images stretch completely, distorting corners and borders.
• Nine-Patch images stretch only selected (marked) regions, preserving visual quality.
• Example: For a button background, create a Nine-Patch image where only the edges stretch —
the corners remain intact while the button grows in size.
5. Pixel Densities (dp and sp)
Android uses Density-independent Pixels (dp) and Scalable Pixels (sp) so UI elements appear the
same physical size across devices with different screen densities.
• dp: Used for layout dimensions, margins, padding. A button defined as 100dp wide appears the
same physical size on all devices.
• sp: Used for text sizes. Same as dp but also scales with the user's preferred font size setting.
6. Alternate Bitmaps
Provide multiple versions of image files at different resolutions to match various screen densities. Place
them in density-specific drawable folders (drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-
xhdpi, etc.). Android automatically loads the appropriate version.
7. Vector Graphics
Use vector graphics (SVG files in Android's VectorDrawable format) for icons and simple images.
Vectors are defined using mathematical paths rather than pixels, so they scale smoothly to any size
without losing quality, eliminating the need for multiple bitmap versions.
8. Specialized Devices
Different Android devices like Wear OS, Android TV, and ChromeOS have unique interaction models
requiring tailored UI designs:
• Wear OS: Circular interface optimized for touch and swipe gestures on small round screens.
• Android TV: Large thumbnails, D-pad/remote navigation, voice search.
• ChromeOS: Keyboard and mouse/trackpad support, resizable windows.
9. Foldables
Foldable devices can have multiple screens or change aspect ratios when folded/unfolded, requiring
dynamic UI adjustments. An app might display a single column in folded mode and expand to a multi-
column layout when unfolded.
Q2. Provide a detailed explanation on how Android supports different pixel densities.
Introduction to Pixel Density
Pixel density, measured in pixels per inch (PPI) or dots per inch (DPI), refers to how many pixels are
packed into a given physical space on the screen. Android devices come in various sizes — phones,
tablets, TVs — with very different screen resolutions. A low-density screen might have 120 PPI while a
high-density screen might have 640 PPI.
The Problem with Using Raw Pixels
If UI dimensions are defined in pixels (px), the same number of pixels will cover different physical sizes
on screens with different densities. For example, a button that is 100 pixels wide would look much
larger on a low-density screen than on a high-density screen. This inconsistency makes the app's UI
look awkward or distorted across different devices.
Solution 1: Density-Independent Pixels (dp)
Android provides a unit called density-independent pixels (dp or dip). The dp unit is tied to the physical
size of the screen, ensuring UI elements maintain consistent physical sizes regardless of screen
density. 1 dp equals 1 pixel on a 160 DPI (mdpi) baseline screen. On higher-density screens, more
pixels are used to represent 1 dp; on lower-density screens, fewer pixels are used.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_marginTop="20dp" />
A button with 20dp margin will appear the same physical size on all devices.
Solution 2: Scalable Pixels (sp) for Text
For text sizes, Android offers scalable pixels (sp). The sp unit is like dp but also scales according to the
user's preferred text size setting in Accessibility options. This ensures text remains readable across
different devices and accommodates users who need larger fonts.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
Android Density Buckets:
Android categorizes screens into several density buckets. Developers should provide separate bitmap
images for each:
Density Approx DPI Scale Factor Description Example Devices
ldpi ~120 dpi 0.75x Low-density Old low-resolution
screens. Images are phones, embedded
smaller. devices
mdpi ~160 dpi 1x (Baseline) Baseline density. UI Early Android
design created here smartphones
first. (Galaxy series)
hdpi ~240 dpi 1.5x High-density Mid-range
screens. Images smartphones
slightly larger.
xhdpi ~320 dpi 2x Extra-high density. Modern Android
Used by many smartphones
modern phones.
xxhdpi ~480 dpi 3x Very high High-end phones
resolution. Sharp like Samsung
graphics. Galaxy S series
xxxhdpi ~640 dpi 4x Ultra-high resolution Premium flagship
displays. phones
nodpi Any None (no scaling) Resources that Background
should not be patterns, fixed-size
scaled. images
tvdpi ~213 dpi 1.33x Used for televisions. Android TV
applications

Solution 3: Alternate Bitmaps


Provide multiple versions of image files at different resolutions in density-specific drawable resource
folders. Android automatically loads the appropriate version based on the device's screen density:
• drawable-ldpi/ — 0.75x resolution images
• drawable-mdpi/ — 1x (baseline) resolution images
• drawable-hdpi/ — 1.5x resolution images
• drawable-xhdpi/ — 2x resolution images
• drawable-xxhdpi/ — 3x resolution images
• drawable-xxxhdpi/ — 4x resolution images
If you don't provide density-specific versions, Android automatically scales the baseline image, which
can cause blurry or distorted results on higher-density screens.
Solution 4: Vector Graphics
Vector graphics are images defined using mathematical paths instead of pixels. They scale smoothly to
any size without losing quality, eliminating the need for multiple bitmap versions. In Android, vector
graphics are stored as VectorDrawable XML files in the drawable/ folder (no density suffix needed).
• Example: Use a VectorDrawable icon (ic_star.xml) instead of PNG files (ic_star.png in multiple
drawable folders). The vector icon looks crisp on all screen densities.
Solution 5: Nine-Patch Images
Nine-Patch images (.[Link]) allow specific areas of a bitmap to stretch while others remain fixed. This is
useful for button backgrounds and dialog frames where only the center should stretch and corners
should remain unchanged.
Best Practices Summary:
• Always use dp for layout dimensions and margins (never px).
• Always use sp for text sizes (never px or dp for text).
• Provide bitmap assets in multiple density folders (mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi).
• Prefer VectorDrawables for icons and simple graphics.
• Use Nine-Patch images for stretchable backgrounds.
• Test the app on multiple screen sizes and densities using the Android Emulator.
Q3. Why is pixel density important for Android app development?
Introduction
Pixel density refers to the number of pixels packed into a physical unit of screen space, measured as
DPI (dots per inch) or PPI (pixels per inch). Understanding pixel density is fundamental to Android app
development because the vast ecosystem of Android devices ranges from budget phones with low-
density screens to premium flagships with ultra-high-density displays.
Reason 1: Ensuring Consistent Visual Appearance
If dimensions are specified in raw pixels, a UI element will appear drastically different in physical size
on devices with different pixel densities. A button 100px wide would appear very large on a 120 DPI
screen (ldpi) but tiny on a 480 DPI screen (xxhdpi). By using density-independent pixels (dp),
developers ensure that UI elements appear the same physical size across all devices regardless of
pixel density.
Reason 2: Image Quality and Clarity
Providing images in a single resolution and letting Android scale them leads to blurry or pixelated
graphics on high-density screens. By providing separate bitmap versions for each density bucket (ldpi,
mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi), developers ensure crisp, clear images on every device. Vector
graphics provide an even better solution for icons and simple shapes, as they are resolution-
independent by nature.
Reason 3: Responsive and Adaptive UX
Different screen densities often correlate with different device classes and use cases. A low-density
device might be a budget phone used differently than a high-density premium flagship. Understanding
density helps developers design layouts and experiences appropriate for each device type. For
example, a high-density tablet might warrant a more information-dense layout than a low-density
phone.
Reason 4: Accessibility and Readability
Text size must also account for density and user preferences. Using sp (scalable pixels) for text sizes
ensures text scales properly with both the screen density and the user's accessibility font size
preference. This is critical for users who need larger text due to visual impairments.
Reason 5: Performance Optimization
Loading inappropriately large images on low-density devices wastes memory and processing power.
Loading undersized images on high-density devices forces upscaling, wasting quality. Proper density
management (alternate bitmaps + VectorDrawables) ensures optimal memory usage and rendering
performance across the full device spectrum.
Real-World Impact:
• A 48x48dp icon appears 36x36 pixels on ldpi, 48x48 on mdpi, 72x72 on hdpi, 96x96 on xhdpi,
144x144 on xxhdpi, and 192x192 on xxxhdpi — all the same physical size.
• An app ignoring pixel density will have distorted UI on most devices, leading to poor reviews
and user experience.
Conclusion: Pixel density awareness is a fundamental requirement for building high-quality Android
apps. Using dp for layout dimensions, sp for text, providing alternate bitmap resources, and leveraging
vector graphics are the core practices that ensure a consistent, accessible, and visually appealing app
across the diverse Android device ecosystem.
Q4. Write a detailed note on Android TV, Android Auto, and Android Things with examples.
Android has been adapted for various specialized devices beyond traditional smartphones and tablets.
Each platform has unique requirements, interaction models, and use cases.
1. Android TV
Android TV is an Android platform specifically optimized for large-screen entertainment experiences in
living room settings. Unlike smartphones with touchscreens, Android TV is designed to be controlled
using remote controls, game controllers, or voice commands via Google Assistant.
Key Characteristics:
• Large-screen UI: The interface uses large thumbnails, bold typography, and a leanback (10-foot
UI) design philosophy optimized for viewing at distance.
• Input methods: Relies on D-pad navigation (up/down/left/right/select) via remote control rather
than touch.
• Content-focused: Designed for browsing movies, TV shows, music, and games.
• Voice search: Integrated Google Assistant for voice-based search and control.
• Leanback library: Android provides the 'Leanback Support Library' specifically for building
Android TV UIs.
• App visibility: Android TV apps are discovered through the Android TV home screen launcher.
Development Considerations:
• Must support D-pad navigation (every focusable element must be reachable via remote).
• No touchscreen support — tap events should not be the only interaction method.
• Use large text and high-contrast colors for readability from a distance.
• Declare in [Link] that the app supports the leanback feature.
Example:
A streaming app like Netflix on Android TV presents a simple, easy-to-navigate interface with large
content thumbnails organized in horizontal rows by category (Continue Watching, New Releases, etc.).
Users navigate using their TV remote, select content to watch, and use voice search to find specific
titles. The UI is designed for clarity from 10 feet away on a large TV screen.
2. Android for Cars (Android Auto and Android Automotive OS)
Android has two distinct approaches for in-car experiences:
Android Auto:
• A mobile app that mirrors features from an Android smartphone to a car's infotainment display.
• The phone is physically connected (USB) or wirelessly connected to the car's head unit.
• Provides navigation (Google Maps/Waze), music, calls, and messaging on the car's screen.
• Controlled via the car's touchscreen or physical buttons, plus voice commands.
• The app runs on the phone — the car just displays the mirrored interface.
Android Automotive OS:
• A full operating system that runs directly on the car's hardware (not dependent on a phone).
• Provides deeper integration with vehicle controls — climate, seat position, vehicle status.
• Apps are installed directly on the car's infotainment system.
• Used by manufacturers like Volvo, Polestar, Renault, and others.
Development Considerations for Android Auto:
• Driver safety is the top priority — minimal driver distraction is mandatory.
• Apps must not show complex UIs. Only approved app categories: navigation, media, and
messaging.
• Must support voice interaction (Google Assistant).
• Large touch targets for easy use without looking away from the road.
Example:
Google Maps for Android Auto allows drivers to use voice commands to search for destinations, view
turn-by-turn navigation directions on the car's display, receive traffic alerts, and control playback — all
without taking their eyes off the road. The interface shows only essential information in large, high-
contrast text.
3. Android Things
Android Things is a lightweight version of Android designed specifically for Internet of Things (IoT)
devices. It allows developers to build smart connected devices using familiar Android tools, APIs, and
programming languages (Java/Kotlin).
Key Characteristics:
• Designed for embedded and constrained devices — low memory, limited processing power, no
traditional display.
• Supports hardware I/O: GPIO (General Purpose Input/Output), I2C, SPI, UART for connecting
sensors and actuators.
• Uses standard Android development tools: Android Studio, ADB, SDK.
• Supports Google services: Cloud IoT Core, Firebase, TensorFlow Lite for ML on the edge.
• Simplified OS: Only includes components necessary for IoT — no full Android UI framework.
• Managed updates: Google manages OS updates centrally, ensuring devices stay secure.
Typical Use Cases:
• Smart thermostats, smart locks, industrial sensors, digital signage, vending machines.
• Smart home devices: lights, security cameras, doorbells.
• Retail and hospitality kiosks.
• Connected appliances in the kitchen or factory floor.
Example:
A smart thermostat built with Android Things uses temperature sensors (connected via I2C or GPIO) to
continuously monitor room temperature. The thermostat's Android Things device processes sensor
readings, applies a control algorithm, and sends signals to activate or deactivate the HVAC
(heating/cooling) system. It displays the current temperature on a small touchscreen display and allows
users to adjust preferences remotely via a connected mobile app. The thermostat also sends data to
Google Cloud IoT Core for historical analysis and remote management.
Feature Android TV Android Auto Android Things
Target Device Smart TVs, streaming Car infotainment systems IoT embedded devices
sticks
Input Method Remote control, game Touchscreen, physical Sensors, GPIO, hardware
controller, voice buttons, voice buttons
Primary Use Entertainment content Navigation, media, Smart devices,
messaging while driving automation
Display Large TV screen (60"+) Car dashboard (7"-12") Often no display, or small
embedded
Key Concern 10-foot UI, content Driver safety, minimal Power efficiency,
browsing distraction reliability
Library/Tool Leanback Support Library Car App Library Android Things SDK
Example App Netflix, YouTube, Kodi Google Maps, Spotify, Smart thermostat, smart
WhatsApp lock
— End of Answer Bank —
Based on course notes by Prof. Shagufta Khan

You might also like