📖 2413MJET306A • Unit V • 6 Hrs

Unit V - Content Providers, SQLite Programming and Location Based Services

Comprehensive University Exam Preparation Notes, Model Question Answers & Comparison Matrices

🔍
📑 Quick Jump Navigation

📌 Syllabus Topics Covered

6 Hrs Weightage

📖 Comprehensive Theoretical Notes

Exam-Oriented Theory

5.1 Content Providers & ContentResolver

Content Provider: A core Android component that encapsulates relational data and provides a secure, standardized interface for sharing data across different applications.

Content URI Architecture: Formatted as content://authority/path/id

  • content://: Standard scheme identifying it as a Content URI.
  • authority: Unique package identifier string (e.g., com.example.provider).
  • path: Identifies table or dataset (e.g., /contacts).
  • id: Optional specific record ID (e.g., /contacts/5).

ContentResolver Methods: getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder), insert(), update(), delete().

5.2 - 5.7 SQLite Database Programming in Android

SQLite: A lightweight, serverless, transactional, zero-configuration embedded SQL database engine built into the Android operating system.

SQLiteOpenHelper Abstract Class: Manages database creation and version management:

  • onCreate(SQLiteDatabase db): Executed when database is created for the first time. Executes SQL DDL (db.execSQL("CREATE TABLE ...")).
  • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion): Executed when database version number increases. Drops tables or migrates schemas.

SQLiteDatabase CRUD Operations:

  • Create (Insert): ContentValues values = new ContentValues(); values.put("name", "John"); db.insert("users", null, values);
  • Read (Query): Cursor cursor = db.query("users", projection, "age > ?", new String[]{"18"}, null, null, "name ASC");
  • Update: db.update("users", values, "id = ?", new String[]{"1"});
  • Delete: db.delete("users", "id = ?", new String[]{"1"});

Cursor Navigation: Iterating query results:

if (cursor != null && cursor.moveToFirst()) {
    do {
        int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
        String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
    } while (cursor.moveToNext());
    cursor.close();
}

5.8 & 5.9 JSON Parsing and Location-Based Services (LBS)

Android JSON Parsing:

  • JSONObject jsonObject = new JSONObject(jsonString);
  • String title = jsonObject.getString("title");
  • JSONArray jsonArray = jsonObject.getJSONArray("items");
  • Iterate through array indices: JSONObject item = jsonArray.getJSONObject(i);

Location-Based Services (LBS):

  • Providers: GPS_PROVIDER (high accuracy, satellite based, outdoors) vs NETWORK_PROVIDER (cellular tower / Wi-Fi triangulation, fast, lower battery).
  • FusedLocationProviderClient: Google Play Services unified location API optimizing accuracy and power consumption.
  • Permissions: ACCESS_FINE_LOCATION (GPS accurate to meters) and ACCESS_COARSE_LOCATION (city block accuracy).
  • Geocoder: Forward Geocoding (Address text $\rightarrow$ Latitude/Longitude) and Reverse Geocoding (Latitude/Longitude $\rightarrow$ Street Address).

🔑 Key Concepts & Examination Keywords

Quick Terminology
SQLiteOpenHelper
A helper class that manages database creation, connection caching, and version migration.
Cursor
A pointer object representing a random read-write result set returned by an SQLite database query.
ContentResolver
The client-side API class used to query and mutate data exposed by Content Providers.
FusedLocationProviderClient
The official Google Play Services API providing intelligent power-optimized device location.

🎯 High-Yield Important Examination Questions

8–10 Descriptive Points Each

Q1. Explain SQLite database programming in Android: describe SQLiteOpenHelper (onCreate, onUpgrade), SQLiteDatabase CRUD operations, and Cursor navigation.

10 MarksSQLite DatabaseCore
📝 Detailed Examination Answer (10-Point Model):
  1. Embedded SQLite Engine in Android: SQLite is a serverless, self-contained, transactional relational database engine integrated natively into the Android operating system.
  2. Role of SQLiteOpenHelper: An abstract helper class encapsulating database creation, opening, and version migration logic without hardcoding SQL scripts in UI activities.
  3. onCreate(SQLiteDatabase db) Callback: Fired when the database file is accessed for the very first time; executes table creation DDL scripts via `db.execSQL('CREATE TABLE ...')`.
  4. onUpgrade(SQLiteDatabase db, oldVersion, newVersion): Fired when the database version number increases; drops legacy tables or executes `ALTER TABLE` schema migration scripts.
  5. INSERT Operation via ContentValues: Inserts key-value pairs using `ContentValues values = new ContentValues(); values.put('name', 'Alice'); long id = db.insert('users', null, values);`.
  6. QUERY Operation via db.query(): Queries tables securely: `db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)` avoiding raw SQL string concatenation.
  7. UPDATE Operation: Updates rows matching selection criteria: `db.update('users', values, 'id = ?', new String[]{ '1' })` returning number of affected rows.
  8. DELETE Operation: Deletes specified records: `db.delete('users', 'id = ?', new String[]{ '1' })`.
  9. Cursor Navigation and Reading Columns: Uses `cursor.moveToFirst()`, `cursor.moveToNext()`, extracting typed values via `cursor.getString(columnIndex)` and `cursor.getInt(columnIndex)`.
  10. Mandatory Cursor and Database Closure: Cursors (`cursor.close()`) and database instances (`db.close()`) must be closed to prevent memory leaks and database locks.

Q2. Explain Content Providers in Android: describe their architectural role, Content URIs structure, ContentResolver methods, and interacting with native Contacts.

10 MarksContent Providers
📝 Detailed Examination Answer (10-Point Model):
  1. Need for Content Providers: Android security sandboxes prevent apps from reading each other's private SQLite files; Content Providers provide the standard cross-app data sharing gateway.
  2. Content URI Standard Syntax: Uniform addressing string: `content://authority/path/id` (e.g., `content://com.android.contacts/data`).
  3. Authority Component: A unique string (usually the provider's package name) that Android OS uses to look up the registered provider in system registry.
  4. Path and ID Components: Path identifies the specific data table; trailing integer ID targets a specific individual record row.
  5. Client Interaction via ContentResolver: Client activities never instantiate the Provider directly; they call `getContentResolver().query(uri, ...)` which routes through Android IPC.
  6. ContentProvider 6 Abstract Methods: A custom provider extends `ContentProvider` implementing: `onCreate()`, `query()`, `insert()`, `update()`, `delete()`, and `getType()` (MIME type).
  7. MIME Types (vnd.android.cursor.dir vs .item): Returns directory MIME (`vnd.android.cursor.dir/...`) for multiple rows and item MIME (`vnd.android.cursor.item/...`) for single records.
  8. Interacting with Device Contacts Provider: Queries contacts using URI `ContactsContract.CommonDataKinds.Phone.CONTENT_URI` with runtime permission `READ_CONTACTS`.
  9. Preventing SQL Injection via selectionArgs: Parameterized placeholders (`?`) in selection queries paired with `selectionArgs` prevent malicious SQL injection attacks.
  10. UriMatcher Helper Class: Utility class used inside custom providers to match incoming URI patterns (`URI_ALL_ITEMS = 1`, `URI_SINGLE_ITEM = 2`).

Q3. Describe Location-Based Services (LBS) in Android: compare GPS vs Network providers, FusedLocationProviderClient, and Geocoding APIs.

10 MarksLocation-Based Services
📝 Detailed Examination Answer (10-Point Model):
  1. Foundations of Location-Based Services (LBS): LBS combines mobile hardware sensors, satellite constellations, and cell networks to provide real-time geographic location coordinates (Latitude, Longitude).
  2. GPS Provider Mechanism: Uses Global Positioning System satellite trilateration; offers highest outdoor accuracy (within meters) but consumes high battery and fails indoors.
  3. Network Provider Mechanism: Uses cellular tower IDs and Wi-Fi access point MAC address triangulation; works indoors with low battery consumption but lower accuracy.
  4. Passive Location Provider: Passively receives location updates requested by other applications without triggering GPS hardware, minimizing battery impact.
  5. FusedLocationProviderClient (Google Play Services): Intelligent location engine that automatically blends GPS, Wi-Fi, Cellular, and motion sensors to optimize accuracy and battery life.
  6. LocationRequest Priority Configurations: Configured via `PRIORITY_HIGH_ACCURACY` (GPS), `PRIORITY_BALANCED_POWER_ACCURACY` (Wi-Fi/Cellular), or `PRIORITY_LOW_POWER`.
  7. Runtime Location Permissions: Requires declaring `` and requesting runtime approval on Android 6.0+.
  8. Forward Geocoding via Geocoder API: Converts human-readable address strings (e.g., '1600 Amphitheatre Pkwy, Mountain View') into geographic Latitude and Longitude coordinates.
  9. Reverse Geocoding: Converts raw Latitude and Longitude coordinates into human-readable street addresses, city, state, and postal zip codes.
  10. Proximity Alerts & Geofencing: Monitors geographic circular boundaries (geofences), triggering pending intents when a device enters or exits a predefined perimeter.

⚖️ Comprehensive Comparison & Difference Tables

8+ Comparison Criteria

📊 SharedPreferences vs SQLite Database vs Content Provider

Comparison ParameterSharedPreferencesSQLite DatabaseContent Provider
Data ModelKey-Value pairs stored in an internal XML file.Relational tables with rows, columns, and SQL schemas.Relational data encapsulated behind Content URIs.
Data ComplexitySimple primitive types (int, float, string, boolean).Complex structured relational data, foreign keys, indexes.Complex structured relational data and binary assets.
Inter-App SharingStrictly private to the application; cannot be shared.Private to the application; inaccessible to other apps.Designed specifically for secure cross-application data sharing.
Query CapabilityLookup by key name (`getString("key", default)`).Rich SQL queries (JOIN, WHERE, GROUP BY, ORDER BY).CRUD queries via ContentResolver (`query`, `insert`, etc.).
Performance & SizeUltra-fast for small configuration data (<1MB).High-performance database handling large datasets (MBs to GBs).High-performance with IPC serialization overhead.
Typical Use CasesUser settings, theme toggle, session login tokens.Local offline data caching, e-commerce orders, notes.Exposing contacts, photo gallery, custom app data.
Implementation EffortMinimal effort; single line getter/setter methods.Moderate effort; requires SQLiteOpenHelper and Cursor logic.Higher effort; requires subclassing ContentProvider and URI matching.
Security ModelProtected by Linux UID file system sandbox.Protected by Linux UID file system sandbox.Protected by URI permissions and custom Android permissions.

📊 GPS Provider vs Network Location Provider

Comparison ParameterGPS Location ProviderNetwork Location Provider
Technology UsedGlobal Positioning System satellite signals.Cellular tower IDs and Wi-Fi access point BSSID lookup.
Accuracy LevelHigh accuracy (within 3 to 10 meters).Moderate to low accuracy (within 50 to 500 meters).
Indoor PerformanceFails indoors or in urban canyons (requires direct sky view).Works well indoors, inside basements, and inside buildings.
Time to First Fix (TTFF)Slow; takes 10 to 60 seconds to acquire satellite locks.Ultra-fast; resolves location within 1 to 3 seconds.
Battery ConsumptionHeavy battery consumption (active GPS radio).Low to moderate battery consumption.
Internet RequirementDoes not require internet connection to calculate position.Requires active internet data connection for tower/Wi-Fi lookup.
Declared PermissionRequires `android.permission.ACCESS_FINE_LOCATION`.Can function with `android.permission.ACCESS_COARSE_LOCATION`.
Best ApplicationTurn-by-turn driving navigation, fitness running trackers.Weather lookup by city, localized news, general location awareness.

⚡ Quick Pre-Exam Revision Summary

5-Minute Recap
💡 Core Takeaways & High-Yield Summary
  • SQLite is a serverless, embedded relational database engine in Android.
  • `SQLiteOpenHelper` provides `onCreate()` (initial schema creation) and `onUpgrade()` (version migrations).
  • `SQLiteDatabase` handles CRUD via `insert()`, `query()`, `update()`, and `delete()` using `ContentValues`.
  • Cursor methods: `moveToFirst()`, `moveToNext()`, `getString()`, `getInt()`, `close()`.
  • Content Providers share data across apps via Content URIs (`content://authority/path`) accessed via `ContentResolver`.
  • LBS utilizes `GPS_PROVIDER` (high accuracy, outdoors) and `NETWORK_PROVIDER` (fast, indoors) via `FusedLocationProviderClient`.