Source status: This guide uses an earlier CACS351 outline as a study reference for BCA352. The TU 2025 PDF confirms BCA352 in the course structure but does not provide detailed units there. The earlier compilation includes sections dated 2019, so confirm the edition and current topics with your instructor. This is not official TU 2025 syllabus text.
Course overview
Mobile Programming introduces application development for mobile platforms, centered on Android with an introduction to iOS. Students learn the Android platform, project setup, user-interface design, activities and intents, fragments, menus, dialogs, list-based views, local SQLite storage, remote APIs and JSON, Google Maps integration, app publishing, and iOS/Swift fundamentals. The course pairs theory with practical work (3 hrs theory + 3 hrs practical per week, 3 credits).
Learning outcomes (derived only from the approved TOC)
By the end of this course, a student should be able to:
- Describe mobile device features, categories, history, brands, models, and platforms, and define mobile programming.
- Describe the Android platform, its history, and set up the Android development environment.
- Create an Android project, lay out a user interface using the view hierarchy, widget attributes, string resources, and layout preview.
- Create new classes, set up a project, and run an application on the emulator.
- Use Android layout types (Linear, Relative, Table, Absolute, Constraint) and layout attributes.
- Use Android widgets (TextView, EditText, CheckBox, RadioButton, Spinner and others) and their attributes.
- Handle events, work with strings, string arrays, colors, resources, and drawables, and add an app icon.
- Explain the Activity life cycle, create multiple activities, declare them in the manifest, and connect activities with intents.
- Pass data between activities and get a result back from a child activity.
- Get and set data to and from layout files.
- Explain the need for UI flexibility, the fragment life cycle, create and wire UI fragments, use the fragment manager, and distinguish Activity from Fragments.
- Implement menus and dialogs (including dialog fragments) in an application.
- Implement ListView, GridView, and RecyclerView in an application.
- Use SQLite locally (connection, database and table creation, data manipulation).
- Explain APIs, API types, and JSON; retrieve and send contents to a remote server.
- Implement Google Maps in an Android application.
- Describe the procedure for publishing an application on the Google Play Store.
- Introduce iOS programming, set up the Xcode environment, build an iOS interface, make connections, and run on the simulator.
- Introduce Swift, views and view hierarchy, storyboards and view controllers, widgets and attributes, and create a simple iOS application.
Unit 1: Introduction to Mobile and Mobile Programming
Teaching hours: 2
Topics in outline order
- Mobile Device (Features, Categories, History, Brands, Models and Platforms)
- Introduction to Mobile Programming
1. Mobile Device (Features, Categories, History, Brands, Models and Platforms)
Plain-language definition and why it matters. A mobile device is a small, battery-powered computing device designed to be carried and used anywhere — smartphones, tablets, feature phones, and wearables. Understanding devices matters because mobile apps must adapt to different screen sizes, hardware capabilities, and input methods.
Core theory.
- Features: touchscreen, cellular/Wi-Fi/Bluetooth connectivity, GPS, camera, accelerometer/gyroscope, microphone, speakers, limited battery, limited RAM/storage compared to desktops.
- Categories: smartphones, tablets, feature phones, phablets, wearables (smartwatches, fitness bands).
- History: from early mobile phones (1980s-90s voice/SMS) to smartphones (BlackBerry, Palm, early iPhone/Android era) to today's app-centric touch devices.
- Brands: Apple, Samsung, Google, Xiaomi, OnePlus, Huawei, Nokia, Sony, LG, Motorola.
- Models and platforms: specific device models run platforms — iOS (Apple iPhone/iPad), Android (wide range of manufacturers), KaiOS (feature phones), HarmonyOS, Windows Phone (legacy).
Syntax / notation. No programming syntax; this is conceptual.
Worked example. Device capability check for an app that needs GPS and camera:
- Requirement: app records geotagged photos.
- Device A (modern smartphone): GPS yes, camera yes, touchscreen yes, 4 GB RAM → supported.
- Device B (basic feature phone): GPS no, camera basic, no touchscreen → not supported.
- Decision: declare
android.hardware.location.gpsandandroid.hardware.camerain the manifest so Google Play filters incompatible devices.
Realistic use case. A Nepali e-commerce app must run on low-end Android phones (2 GB RAM) and iPhones; developers test on representative models from each brand/platform and disable camera-dependent features on devices without a camera.
Comparison table.
| Aspect | Smartphone | Tablet | Feature phone | Wearable |
|---|---|---|---|---|
| Screen | large touch | larger touch | small/keypad | tiny |
| OS | Android/iOS | Android/iPadOS | KaiOS/proprietary | watchOS/Wear OS |
| Main use | apps, web, calls | media, reading | calls, SMS | notifications, health |
| RAM/CPU | high | high | low | low |
Swipe to see all columns
Common mistakes / limitations. Treating all mobile devices as identical; assuming always-on fast network or unlimited battery; ignoring screen-size variation.
Exam-ready answer points. Define mobile device; list features, categories, brands; contrast smartphone vs feature phone vs tablet; explain why platforms matter for app distribution.
Self-check questions with answers.
- Name three mobile device features. Answer: touchscreen, GPS, camera (also Wi-Fi, Bluetooth, accelerometer).
- List two smartphone brands and two platforms. Answer: Apple/Samsung; iOS/Android.
2. Introduction to Mobile Programming
Plain-language definition and why it matters. Mobile programming is writing software that runs on mobile devices. It matters because most users now access services through apps, and mobile apps can use device hardware (camera, GPS, sensors) that websites cannot easily access.
Core theory. Mobile programming differs from desktop/web programming in: limited screen real estate, touch input, app lifecycle managed by the OS (apps can be paused/killed), offline-first design, distribution via app stores, and platform-specific SDKs (Android SDK, iOS SDK). Two dominant approaches: native (Java/Kotlin for Android, Swift/Objective-C for iOS) and cross-platform (Flutter, React Native).
Syntax / notation. Conceptual only; examples appear in Android units.
Worked example. Planning a "farmer market price" app:
- Platform choice: Android first (widest reach in target region).
- Screens: price list, add price, map of markets.
- Hardware used: GPS (market location), network (fetch prices).
- Lifecycle: save draft price when app is backgrounded.
Realistic use case. A banking app uses mobile programming to let users check balances and transfer funds using biometrics (fingerprint) and device-bound security.
Comparison: Native vs cross-platform mobile programming.
| Native | Cross-platform | |
|---|---|---|
| Language | Kotlin/Java (Android), Swift (iOS) | Dart (Flutter), JS (React Native) |
| Performance | best, full API access | good, some abstraction overhead |
| Code sharing | none between platforms | high |
| UI | platform-native look | custom/consistent look |
Common mistakes / limitations. Assuming one codebase runs identically everywhere; ignoring app-store review; underestimating battery and memory constraints.
Exam-ready answer points. Define mobile programming; contrast mobile vs desktop programming; list mobile constraints; name native vs cross-platform approaches and give one example each.
Self-check questions with answers.
- Why do mobile apps need to handle being paused/killed? Answer: the OS manages the app lifecycle to save battery and memory.
- Name one native and one cross-platform mobile technology. Answer: Kotlin (native Android), Flutter (cross-platform).
Key terms — Unit 1
Mobile device · smartphone · tablet · feature phone · wearable · platform · iOS · Android · native app · cross-platform · app lifecycle
Unit summary — Unit 1
Mobile devices vary by features, category, brand, model, and platform; mobile programming targets these constraints using platform SDKs, with native and cross-platform as the two main strategies.
Unit 2: Introduction to Android Programming
Teaching hours: 4
Topics in outline order
- Android Platform
- History of Android
- Environment Setup
- Creating an android project
- Laying out the user interface (The view hierarchy, widget attributes, creating string resources, previewing the layout)
- Creating a new class
- Setting up the project
- Running on the Emulator
1. Android Platform
Plain-language definition and why it matters. Android is Google's open-source mobile operating system built on the Linux kernel. It matters because it runs on the widest range of devices globally and is the primary target for this course's practical work.
Core theory. Android stack layers: Linux kernel (drivers, power, memory management), native libraries (C/C++), Android Runtime (ART, runs DEX bytecode), application framework (activity manager, content providers, resource manager, notification manager), and applications. Apps are packaged as APK/AAB. Android uses Java/Kotlin and XML for layouts. Each app runs in its own process with a unique user ID (sandboxing).
Syntax / notation. Conceptual; package naming convention com.example.appname.
Worked example. Identifying the Android version (API level) for an app:
- App targets API 30 (Android 11).
- User device runs API 21 (Android 5.0).
- Since minSdkVersion <= 21 <= compileSdkVersion, the app installs; features requiring API 30+ are guarded at runtime.
Realistic use case. A ride-hailing app targets Android 5.0+ to reach older devices while using location and camera APIs conditionally.
Comparison table.
| Layer | Responsibility |
|---|---|
| Linux kernel | drivers, power, memory, process |
| Native libraries | media, graphics (SurfaceManager), SSL |
| Android Runtime (ART) | runs app code (DEX), garbage collection |
| Application framework | activities, services, content providers, resources |
| Applications | user-installed apps and system apps |
Common mistakes / limitations. Confusing API level with version name; assuming latest Android features work on all devices; ignoring sandbox permissions.
Exam-ready answer points. Describe Android stack layers; explain ART, APK, sandboxing; state why API level/minSdkVersion matter.
Self-check questions with answers.
- What runtime executes Android apps? Answer: Android Runtime (ART).
- What file format packages an Android app? Answer: APK (or AAB for Play Store).
2. History of Android
Plain-language definition and why it matters. Android began as an OS for digital cameras, was acquired by Google in 2005, and launched commercially in 2008. Its history explains version naming, API levels, and why older devices run older Android versions.
Core theory. Key milestones: Android Inc. founded 2003; Google acquisition 2005; Open Handset Alliance 2007; Android 1.0 (2008, HTC Dream/T-Mobile G1); early versions 1.5 Cupcake, 1.6 Donut, 2.0/2.1 Eclair, 2.2 Froyo, 2.3 Gingerbread; 3.0 Honeycomb (tablets); 4.0 Ice Cream Sandwich (phones+tablets unified); 4.1-4.3 Jelly Bean; 4.4 KitKat; 5.0 Lollipop (Material Design, ART replaces Dalvik); 6.0 Marshmallow (runtime permissions); 7.0 Nougat; 8.0 Oreo; 9 Pie; 10; 11; 12; 13; 14. Versions historically had dessert names (up to Pie), then switched to numbers. Dalvik VM was replaced by ART (ahead-of-time compilation).
Syntax / notation. None; version numbering like major.minor and API level integers.
Worked example. A developer wants Material Design: introduced in Android 5.0 (API 21). To use Material components, set minSdkVersion 21 or provide fallbacks for older devices.
Realistic use case. An app supporting Nepal's market must run on Android 5.0+ phones still in use, so the team sets minSdkVersion 21 and tests on API 21 and API 33 emulators.
Comparison: Dalvik vs ART.
| Dalvik | ART |
|---|---|
| Just-in-time (JIT) compilation | Ahead-of-time (AOT) compilation |
| Install faster, run slower | install slower, run faster, better battery |
| Used up to Android 4.4 | default from Android 5.0 |
Common mistakes / limitations. Assuming dessert names continue after Android 9; confusing version name with API level.
Exam-ready answer points. Trace Android from 2003 to present; name key versions and API levels; explain Dalvik→ART; explain version naming change.
Self-check questions with answers.
- Which Android version introduced Material Design? Answer: Android 5.0 Lollipop (API 21).
- What replaced Dalvik? Answer: Android Runtime (ART).
3. Environment Setup
Plain-language definition and why it matters. Environment setup means installing the tools needed to write, build, and test Android apps. It matters because without a working environment, no development can happen.
Core theory. Required components: Java Development Kit (JDK), Android Studio (official IDE, based on IntelliJ), Android SDK (platform tools, build tools, emulator system images), an emulator or physical device, and optionally Gradle. Configure ANDROID_HOME/SDK path, install SDK platforms for target API levels, create an Android Virtual Device (AVD), enable USB debugging on a physical device, and install vendor drivers (Windows).
Syntax / notation. Command: adb devices lists connected emulators/devices.
Worked example. Step-by-step setup:
- Install JDK 17.
- Install Android Studio; run SDK Manager to install platform for API 34, build tools, emulator.
- Open AVD Manager, create Pixel 7 API 34 virtual device, download system image.
- Create new project, wait for Gradle sync.
- Run app → it installs on the emulator and launches.
Realistic use case. A college lab sets up Android Studio on shared PCs; students create AVDs so they don't need physical phones.
Common mistakes / limitations. Forgetting to install the SDK platform matching compileSdkVersion; emulator too slow without hardware acceleration (HAXM/Hypervisor); not enabling USB debugging on physical device.
Exam-ready answer points. List setup components; describe AVD creation; state the role of the SDK Manager and Gradle sync; give the adb devices command.
Self-check questions with answers.
- Name two required components of the Android development environment. Answer: Android Studio/JDK and Android SDK (emulator also acceptable).
- What command lists connected devices/emulators? Answer:
adb devices.
4. Creating an android project
Plain-language definition and why it matters. Creating a project generates the folder structure, build files (Gradle), manifest, and starter code that Android Studio uses to build an app. It matters because every app begins here and the structure must be correct for the build to succeed.
Core theory. In Android Studio: File → New → New Project. Choose a template (Empty Activity), set project name, package name (com.example.myapp), save location, language (Kotlin/Java), minimum SDK. Files generated: build.gradle (project + module), settings.gradle, AndroidManifest.xml, res/ (layouts, drawables, values), src/ (Kotlin/Java source), and a starter MainActivity.
Syntax / notation. Package name example: com.npk.bca.app. Gradle DSL snippet:
android {
compileSdk = 34
defaultConfig {
applicationId = "com.example.myapp"
minSdk = 21
targetSdk = 34
versionCode = 1
versionName = "1.0"
}
}
Worked example. Creating "CropPrice" app:
- Project name: CropPrice; package
com.npk.cropprice; language Kotlin; min SDK 21. - Result:
MainActivity.ktwithonCreate,activity_main.xmlwith aConstraintLayoutand aTextViewsaying "Hello World". - Run on emulator → displays Hello World.
Realistic use case. A student creates a semester project; correct package name avoids collisions when publishing.
Comparison table.
| Item | Purpose |
|---|---|
| packageName/applicationId | unique app identity |
| minSdkVersion | oldest Android version supported |
| compileSdkVersion | Android APIs available while building |
| targetSdkVersion | version the app is tested against |
Common mistakes / limitations. Using a package already published (collision); setting minSdk higher than target users' devices; forgetting to sync Gradle after editing build files.
Exam-ready answer points. Describe project creation steps; list generated files; explain package name, minSdk, compileSdk, targetSdk.
Self-check questions with answers.
- What is the unique identity of an Android app? Answer: applicationId / package name.
- Which file declares app components and permissions? Answer: AndroidManifest.xml.
5. Laying out the user interface (The view hierarchy, widget attributes, creating string resources, previewing the layout)
Plain-language definition and why it matters. Layout defines how widgets (buttons, text fields, images) are arranged on screen using the View/ViewGroup hierarchy. It matters because UI is the user's main interaction point and must look right on many screen sizes.
Core theory. View hierarchy: root ViewGroup (e.g., ConstraintLayout) containing Views (widgets) and nested ViewGroups. Each view has attributes: layout_width, layout_height, id, text, padding, margin, gravity, layout_gravity, background. String resources live in res/values/strings.xml and are referenced as @string/name so the app can be localized and strings aren't hardcoded. Android Studio's Layout Editor provides Design (drag-drop) and Code (XML) views plus a preview pane.
Syntax / notation. XML layout:
<TextView
android:id="@+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textSize="18sp" />
@+id/ creates a new resource ID; @string/ references an existing string. dp = density-independent pixels; sp = scale-independent pixels (for text).
Worked example. Build a login screen:
- Root: ConstraintLayout.
- TextView "Welcome" constrained to top center.
- EditText for username, EditText for password, Button "Login" vertically chained.
- strings.xml:
<string name="login_button">Login</string>, referenced as@string/login_button. - Preview shows the layout on a Pixel 7 device.
Realistic use case. A registration form uses string resources so the same app can later be translated into Nepali without changing layout code.
Comparison table.
| Unit | Meaning | Use |
|---|---|---|
| dp | density-independent pixels | layout sizes |
| sp | scale-independent pixels | text sizes |
| wrap_content | size to fit content | width/height |
| match_parent | fill parent | width/height |
Common mistakes / limitations. Hardcoding strings instead of strings.xml; using sp for non-text sizes; forgetting android:id on views referenced in code; ignoring different screen sizes in preview.
Exam-ready answer points. Explain view hierarchy; list common view attributes; explain string resources and @string/; explain dp vs sp; describe the Layout Editor preview.
Self-check questions with answers.
- What does
@+id/do in XML? Answer: creates and declares a new resource ID. - Difference between dp and sp? Answer: dp for layout sizes, sp for text sizes (respects user font scale).
6. Creating a new class
Plain-language definition and why it matters. Adding a new Java/Kotlin class lets you create activities, adapters, models, or helper logic beyond the starter MainActivity. It matters because real apps are made of many cooperating classes.
Core theory. In Android Studio: File → New → Java/Kotlin Class (or Activity/Fragment). Choose name (PascalCase, e.g., UserProfile), superclass if any (e.g., AppCompatActivity), and whether to add layout XML. For an activity class, also register it in AndroidManifest.xml with <activity android:name=".UserProfile" />.
Syntax / notation. Kotlin activity:
class UserProfile : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_profile)
}
}
Worked example. Add ProductDetail activity:
- New → Kotlin Class named
ProductDetail, superclassAppCompatActivity. - Create
activity_product_detail.xml. - In
onCreate,setContentView(R.layout.activity_product_detail). - Register in manifest:
<activity android:name=".ProductDetail" android:exported="false" />. - Launch from MainActivity with an Intent.
Realistic use case. A product catalog app has one class per screen: ProductList, ProductDetail, Cart, Checkout.
Common mistakes / limitations. Forgetting manifest registration (crash on launch); wrong superclass; mismatched layout file name.
Exam-ready answer points. Steps to create a class/activity; manifest registration requirement; Kotlin class syntax for an activity.
Self-check questions with answers.
- Why must a new Activity be registered in AndroidManifest.xml? Answer: the system needs to know the component exists to launch it.
- Naming convention for Kotlin classes? Answer: PascalCase (e.g., UserProfile).
7. Setting up the project
Plain-language definition and why it matters. Project setup configures Gradle, dependencies, SDK versions, signing config, and app resources so the app builds and runs. It matters because misconfiguration causes build failures or runtime crashes.
Core theory. Module-level build.gradle.kts sets compileSdk, minSdk, targetSdk, versionCode/name, dependencies (e.g., implementation("androidx.appcompat:appcompat:1.6.1")), and build types (debug/release). AndroidManifest.xml declares components (activities, services, receivers, providers), permissions (<uses-permission>), and app icon/theme. strings.xml, colors.xml, themes.xml hold resources.
Syntax / notation. Gradle dependency example: implementation("com.google.android.material:material:1.11.0").
Worked example. Add internet permission and Material dependency:
- Manifest:
<uses-permission android:name="android.permission.INTERNET" />. - Gradle: add
implementation("com.google.android.material:material:1.11.0"), sync, rebuild.
Realistic use case. A news app needs INTERNET permission to fetch articles and Material Components for a modern UI.
Comparison table.
| File | Holds |
|---|---|
| build.gradle.kts | SDK versions, dependencies, build types |
| AndroidManifest.xml | components, permissions, icon, theme |
| strings.xml | user-visible text |
| themes.xml | app colors, typography, shape |
Common mistakes / limitations. Declaring permission in manifest but not requesting runtime permissions (Android 6.0+); versionCode not incremented before an update; incompatible dependency versions.
Exam-ready answer points. List setup files and their purpose; explain Gradle dependencies; explain manifest permissions.
Self-check questions with answers.
- Where are runtime permissions declared for Android 6+? Answer: in AndroidManifest.xml (
uses-permission) and requested at runtime. - What must be incremented for a Play Store update? Answer: versionCode.
8. Running on the Emulator
Plain-language definition and why it matters. The emulator (Android Virtual Device) runs Android on the development computer so apps can be tested without a physical device. It matters for rapid iteration and testing across device types and API levels.
Core theory. Create an AVD in Device Manager (choose device definition, system image/API level). Launch it; Android Studio installs the app via ADB and runs it. The emulator mimics sensors, GPS, calls, SMS, and rotation. Hot Reload / Apply Code Changes pushes small edits without full reinstall. Performance improves with hardware acceleration (Intel HAXM, Apple Hypervisor, or Windows Hypervisor Platform).
Syntax / notation. adb -s emulator-5554 install app.apk; adb logcat shows logs.
Worked example. Run app on emulator:
- Create Pixel 6 API 33 AVD.
- Click Run (green triangle) in Android Studio.
- Emulator boots, app installs, MainActivity appears.
- Click rotation button → screen rotates; app handles config change.
- View logs in Logcat tab.
Realistic use case. Testing tablet layout on a 10-inch tablet AVD without owning a tablet.
Common mistakes / limitations. Emulator very slow without hardware acceleration; not all hardware (camera, fingerprint) fully emulated; app behaves differently on emulator vs real device (always test on real device before release).
Exam-ready answer points. Describe AVD creation and running an app; state emulator purpose; mention ADB and Logcat; note hardware acceleration.
Self-check questions with answers.
- What is an AVD? Answer: Android Virtual Device, an emulator configuration.
- Which tool shows device logs while running? Answer: Logcat / adb logcat.
Key terms — Unit 2
Android platform · API level · SDK · AVD · emulator · ADB · Gradle · manifest · package name · view hierarchy · dp · sp · string resource · Logcat
Unit summary — Unit 2
Android is built on a layered stack running under ART; development requires JDK, Android Studio, SDK, and an AVD; projects are created with package name and SDK settings; UIs use the view hierarchy with XML attributes and string resources; classes/activities must be registered in the manifest; apps run on emulator or device via ADB.
Unit 3: Designing the User Interface
Teaching hours: 5
Topics in outline order
- Android layout types (Linear, Relative, Table, Absolute, Constraint)
- Layout attributes
- Android widgets (TextView, EditText, CheckBox, RadioButton, Spinner etc.) and its attributes
- Event Handling
- working with string
- string array and colors
- working with resources and drawable
- adding icon to the project
1. Android layout types (Linear, Relative, Table, Absolute, Constraint)
Plain-language definition and why it matters. Layout types (ViewGroup subclasses) determine how child views are positioned on screen. Choosing the right layout affects how well the UI adapts to different screen sizes and how complex the view hierarchy is.
Core theory.
- LinearLayout: children arranged in a single row (horizontal) or column (vertical); uses
layout_weightto share space. - RelativeLayout: children positioned relative to each other or the parent (e.g., "below", "alignParentRight"). Largely legacy; replaced by ConstraintLayout.
- TableLayout: children arranged in rows and columns using TableRow.
- AbsoluteLayout: children placed at exact x,y coordinates (deprecated; does not adapt to screens).
- ConstraintLayout: children positioned by constraints to siblings/parent edges, guidelines, barriers, and chains; flat hierarchy, best for complex UIs, default in Android Studio.
Syntax / notation.
<LinearLayout android:orientation="vertical" ...>
<Button ... />
</LinearLayout>
<ConstraintLayout ...>
<Button android:id="@+id/btn"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</ConstraintLayout>
app: namespace is for ConstraintLayout attributes.
Worked example. A signup form:
- Vertical LinearLayout containing: TextView title, EditText email, EditText password, Button Register.
- Set
layout_width="match_parent",layout_height="wrap_content",layout_weight="1"on two buttons to share a row equally.
Realistic use case. A settings screen uses ConstraintLayout to keep a flat hierarchy and adapt to small and large screens.
Comparison table.
| Layout | Arrangement | Best for | Status |
|---|---|---|---|
| LinearLayout | row/column | simple lists, forms | common |
| RelativeLayout | relative positioning | moderate complexity | legacy |
| TableLayout | rows/columns | tabular data | occasional |
| AbsoluteLayout | fixed x,y | none (not screen-adaptive) | deprecated |
| ConstraintLayout | constraints/chains | complex, responsive UIs | recommended |
Swipe to see all columns
Common mistakes / limitations. Nesting too many LinearLayouts (deep hierarchy slows rendering); using AbsoluteLayout (breaks on other screens); forgetting app: namespace for ConstraintLayout attributes.
Exam-ready answer points. Describe each layout type; contrast Linear vs Relative vs Constraint; explain why ConstraintLayout is recommended; explain layout_weight.
Self-check questions with answers.
- Which layout is recommended for complex UIs? Answer: ConstraintLayout.
- Which layout is deprecated and should not be used? Answer: AbsoluteLayout.
2. Layout attributes
Plain-language definition and why it matters. Layout attributes control a view's size, position, spacing, and appearance within its parent. They matter because they determine how the UI looks and behaves.
Core theory. Key attributes: layout_width/layout_height (match_parent, wrap_content, or fixed dp), layout_margin (space outside view), layout_marginStart/End/Top/Bottom, layout_padding (space inside view), layout_gravity (child's position within parent), gravity (content alignment inside view), layout_weight (space sharing in LinearLayout), visibility (visible/gone/invisible), background, textColor, textSize, id.
Syntax / notation. android:layout_width="match_parent"; dimension values like 16dp, 18sp; android:visibility="gone" removes the view from layout entirely.
Worked example. A button centered at bottom:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:text="Submit" />
in a vertical LinearLayout.
Realistic use case. A chat app uses padding inside message bubbles and margin between bubbles for readability.
Comparison table.
| Attribute | Affects | Example |
|---|---|---|
| margin | space outside view | separates siblings |
| padding | space inside view | text inside a button |
| gravity | content inside view | center text in TextView |
| layout_gravity | view inside parent | center button in layout |
Common mistakes / limitations. Confusing margin with padding; using fixed dp widths that overflow on small screens; setting visibility="invisible" (still takes space) when "gone" was intended.
Exam-ready answer points. List width/height modes; distinguish margin vs padding vs gravity vs layout_gravity; explain wrap_content vs match_parent.
Self-check questions with answers.
- Difference between margin and padding? Answer: margin is outside a view; padding is inside.
- What does
visibility="gone"do? Answer: removes view from layout (takes no space).
3. Android widgets (TextView, EditText, CheckBox, RadioButton, Spinner etc.) and its attributes
Plain-language definition and why it matters. Widgets are the interactive and display elements (Views) users touch and read. Choosing the right widget with correct attributes makes an app usable and accessible.
Core theory.
- TextView: read-only text; attributes
text,textSize,textColor,gravity,lineSpacingExtra. - EditText: editable text; attributes
inputType(text, number, email, password),hint,maxLines. - CheckBox: togglable boolean; attribute
checked. - RadioButton: single-choice within a RadioGroup (only one selected); attribute
checked. - Spinner: dropdown list; populated via adapter from array/resource.
- Button: clickable action; attribute
text,onClick. - ImageView: shows drawable; attribute
src,scaleType. - ProgressBar: shows loading;
style,indeterminate.
Syntax / notation. EditText example:
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="@string/email_hint" />
Worked example. A registration form:
- TextView title, EditText email (
inputType="textEmailAddress"), EditText password (inputType="textPassword"), CheckBox "I agree", RadioButton gender in RadioGroup, Spinner for country, Button Submit.
Realistic use case. A login screen uses EditText with inputType="textPassword" so the password is masked.
Comparison table.
| Widget | User action | Typical attribute |
|---|---|---|
| TextView | read | text, textSize |
| EditText | type | inputType, hint |
| CheckBox | toggle | checked |
| RadioButton | pick one (group) | checked |
| Spinner | pick from list | entries/adapter |
| Button | tap | onClick, text |
Common mistakes / limitations. RadioButtons outside a RadioGroup allow multiple selections; EditText without inputType shows wrong keyboard; Spinner needs an adapter to show items.
Exam-ready answer points. List common widgets and attributes; explain RadioGroup behavior; explain EditText inputType.
Self-check questions with answers.
- Which widget lets the user pick exactly one from a group? Answer: RadioButton inside a RadioGroup.
- Which EditText attribute masks typed text? Answer:
inputType="textPassword".
4. Event Handling
Plain-language definition and why it matters. Event handling makes the app respond to user actions (clicks, text changes, touches). Without it, the UI is static.
Core theory. In Kotlin, set a listener on a view: button.setOnClickListener { ... }. For XML, use android:onClick="methodName" with a public method in the activity (less common now). Listeners: OnClickListener (click), OnLongClickListener, OnFocusChangeListener, TextWatcher (text changes), OnItemSelectedListener (Spinner). The lambda receives the view that triggered the event.
Syntax / notation. Kotlin:
val btn: Button = findViewById(R.id.submit)
btn.setOnClickListener {
val email = emailEditText.text.toString()
Toast.makeText(this, "Submitted $email", Toast.LENGTH_SHORT).show()
}
Worked example. Login button click:
- Find views by ID.
loginButton.setOnClickListener { }.- Inside: read email/password EditTexts, validate non-empty, show Toast or start next activity.
Realistic use case. A calculator app: each digit button click appends to the display; equals click computes and shows result.
Comparison table.
| Listener | Trigger | Use |
|---|---|---|
| OnClickListener | tap | buttons |
| OnLongClickListener | long press | context actions |
| TextWatcher | text changed | live validation |
| OnItemSelectedListener | spinner pick | form fields |
Common mistakes / limitations. Calling findViewById before setContentView (null view); performing network calls on the main thread (crash); forgetting to cast the view when using one listener for multiple buttons.
Exam-ready answer points. Explain event handling; show Kotlin listener syntax; name common listeners; explain main-thread restriction.
Self-check questions with answers.
- Which listener responds to a button tap? Answer: OnClickListener.
- Why not do network calls in a click listener? Answer: they block the main (UI) thread and crash the app.
5. working with string
Plain-language definition and why it matters. Strings are text used in the app (labels, messages). Keeping them in strings.xml instead of hardcoded enables translation, reuse, and easier updates.
Core theory. res/values/strings.xml contains <string name="key">text</string>. Reference in XML as @string/key; in Kotlin as getString(R.string.key) or resources.getString(R.string.key). String formatting with placeholders: <string name="welcome">Hello, %1$s!</string> → getString(R.string.welcome, name). Use <string-array> for lists.
Syntax / notation.
XML: <string name="app_name">MyApp</string>
Kotlin: val title = getString(R.string.app_name)
Worked example. Welcome message with name:
- strings.xml:
<string name="welcome_msg">Welcome, %1$s!</string> - Kotlin:
val msg = getString(R.string.welcome_msg, userName)→ "Welcome, Sita!"
Realistic use case. An app shows the logged-in user's name dynamically in the header using a formatted string resource.
Common mistakes / limitations. Hardcoding strings in layout/code (blocks localization); wrong placeholder count causes runtime exception; forgetting name attribute.
Exam-ready answer points. Explain strings.xml; show @string/ XML reference and getString() Kotlin reference; explain string formatting with %1$s.
Self-check questions with answers.
- How do you reference a string in XML? Answer:
@string/key. - How do you get a string in Kotlin? Answer:
getString(R.string.key).
6. string array and colors
Plain-language definition and why it matters. String arrays hold lists (e.g., countries, categories) used by Spinners; colors define the app's visual theme consistently.
Core theory. <string-array name="countries"> with <item> elements in res/values/arrays.xml (or strings.xml). Reference as @array/countries; in Kotlin resources.getStringArray(R.array.countries). Colors in res/values/colors.xml: <color name="primary">#6200EE</color>; referenced as @color/primary in XML or R.color.primary in Kotlin. Colors support #RGB, #ARGB, #RRGGBB, #AARRGGBB.
Syntax / notation.
<string-array name="planets">
<item>Mercury</item><item>Venus</item>
</string-array>
<color name="accent">#03DAC6</color>
Worked example. Country Spinner:
- arrays.xml defines
<string-array name="countries">. - In activity:
val countries = resources.getStringArray(R.array.countries), pass toArrayAdapter, set on Spinner. - Theme uses
@color/primaryfor the colorPrimary attribute.
Realistic use case. A travel app lets users pick a country from a Spinner populated from a string array, and brands the app with a primary color from colors.xml.
Comparison table.
| Resource | File | Reference | Use |
|---|---|---|---|
| string array | arrays.xml | @array/name | Spinner lists |
| color | colors.xml | @color/name | theming, backgrounds |
Swipe to see all columns
Common mistakes / limitations. Missing <item> tags; referencing a color that doesn't exist (build error); using color directly as int instead of ContextCompat.getColor().
Exam-ready answer points. Explain string-array and colors.xml; show XML and Kotlin references; explain color hex formats.
Self-check questions with answers.
- Where are string arrays defined? Answer: arrays.xml (or strings.xml) as
<string-array>. - What is the color reference syntax in XML? Answer:
@color/name.
7. working with resources and drawable
Plain-language definition and why it matters. Resources are non-code assets (images, icons, layouts, values) kept in res/. Drawables are image resources. Keeping resources separate from code lets the app adapt to screen density, language, and configuration without code changes.
Core theory. res/drawable/ holds PNG, JPG, WebP, XML vector drawables, shape drawables, state lists. Density folders: drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi, drawable-xxxhdpi for bitmap assets so they look sharp on all screens. Vector drawables (XML) scale without quality loss and are preferred for icons. Resources class / R.drawable.name references them. ImageView uses android:src="@drawable/ic_name". Shape drawables define backgrounds (rounded corners, gradients) in XML.
Syntax / notation.
<ImageView android:src="@drawable/ic_launcher" android:contentDescription="Logo" />
Worked example. Add an app icon and a button background:
- Place
ic_logo.pngindrawable-xxhdpiand equivalents in other density folders (or use one vectoric_logo.xmlin drawable). - ImageView
android:src="@drawable/ic_logo". - Button background:
res/drawable/rounded_button.xmlwith<shape>rounded corners and solid color; set asandroid:background="@drawable/rounded_button".
Realistic use case. A news app shows category icons as vector drawables so they stay crisp on low- and high-density screens.
Comparison table.
| Resource type | Folder | Scales? | Typical use |
|---|---|---|---|
| Bitmap (PNG/WebP) | drawable-[dpi] | provide per density | photos |
| Vector drawable | drawable/ | yes (XML) | icons |
| Shape drawable | drawable/ | yes | backgrounds, buttons |
Swipe to see all columns
Common mistakes / limitations. Providing only one bitmap density (blurry on some screens); forgetting contentDescription on ImageView (accessibility); large bitmaps causing OutOfMemoryError.
Exam-ready answer points. Explain resources and drawables; list density folders; explain vector vs bitmap drawables; show ImageView src reference.
Self-check questions with answers.
- Why use vector drawables? Answer: they scale without quality loss across screen densities.
- Which folder holds high-density bitmaps? Answer: drawable-xhdpi (among hdpi/xhdpi/xxhdpi/xxxhdpi).
8. adding icon to the project
Plain-language definition and why it matters. The app icon (launcher icon) identifies the app on the home screen and Play Store. It matters for branding and user recognition.
Core theory. Launcher icon lives in res/mipmap/ (not drawable) because mipmap folders keep resolution for launcher icons across densities: mipmap-mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi. Declared in manifest android:icon="@mipmap/ic_launcher" and android:roundIcon="@mipmap/ic_launcher_round". Android Studio's Image Asset Studio generates adaptive icons (foreground/background layers) for modern Android.
Syntax / notation. Manifest: android:icon="@mipmap/ic_launcher".
Worked example. Replace default icon:
- File → New → Image Asset; choose source image, select "Launcher Icons (Adaptive and Legacy)".
- Android Studio generates
ic_launcher.xmlin mipmap folders with foreground/background. - Manifest already references
@mipmap/ic_launcher; rebuild and install → new icon shows on home screen.
Realistic use case. A college app uses its logo as the launcher icon so students recognize it instantly.
Common mistakes / limitations. Placing icon in drawable instead of mipmap; forgetting roundIcon for circle-icon launchers; adaptive icon foreground must be vector or properly sized.
Exam-ready answer points. Explain where launcher icons live (mipmap); explain adaptive icons; show manifest icon reference; mention Image Asset Studio.
Self-check questions with answers.
- Where are launcher icons stored? Answer: res/mipmap/ folders.
- What manifest attribute sets the app icon? Answer:
android:icon.
Key terms — Unit 3
LinearLayout · RelativeLayout · ConstraintLayout · TableLayout · AbsoluteLayout · layout_weight · widget · TextView · EditText · CheckBox · RadioButton · Spinner · event listener · OnClickListener · strings.xml · string-array · colors.xml · drawable · mipmap · adaptive icon
Unit summary — Unit 3
UIs combine layout types (ConstraintLayout recommended), attributes (width/height/margin/padding/gravity/weight), and widgets (TextView, EditText, CheckBox, RadioButton, Spinner, Button). Events are handled with listeners (OnClickListener etc.). Strings, arrays, colors, and drawables live in res/ as resources referenced by @name; launcher icons use mipmap/adaptive icons.
Unit 4: Android Activity
Teaching hours: 4
Topics in outline order
- The Activity life cycle
- Creating multiple activities
- Declaring activities in the manifest
- Connecting activities with intents
- Passing data between activities
- Getting a result back from a child activity
- Getting and setting data to/from the layout file
1. The Activity life cycle
Plain-language definition and why it matters. An Activity is a single screen with a UI. Its life cycle is the sequence of states the OS moves it through (created, started, resumed, paused, stopped, destroyed). It matters because developers must save/restore data and release resources at the right times or the app loses state or leaks memory.
Core theory. Callbacks in order: onCreate() (initialize, setContentView), onStart() (visible), onResume() (foreground/interactive), onPause() (partially obscured, commit unsaved changes), onStop() (not visible, release heavy resources), onRestart() (coming back from stopped), onDestroy() (final cleanup). Configuration change (rotation) destroys and recreates the activity unless handled; use onSaveInstanceState/onRestoreInstanceState or ViewModel to survive.
Syntax / notation. Kotlin override:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("key", value)
}
Worked example. Rotation with a counter:
onCreate: restore count fromsavedInstanceStateif not null, else 0.- Button increments count; display in TextView.
onSaveInstanceState:outState.putInt("count", count).- Rotate → activity recreated, count restored from Bundle.
Realistic use case. A form partially filled survives screen rotation because text is saved in onSaveInstanceState.
Comparison table.
| Callback | When | Typical work |
|---|---|---|
| onCreate | first created | init UI, bind data |
| onResume | foreground | start sensors/camera |
| onPause | losing focus | pause animations, save draft |
| onStop | hidden | release heavy resources |
| onDestroy | finishing | final cleanup |
Common mistakes / limitations. Doing heavy work in onCreate (slow launch); assuming instance state survives process death (it doesn't — use persistent storage); leaking context in callbacks.
Exam-ready answer points. List life-cycle callbacks in order; explain each; explain rotation handling and instance state.
Self-check questions with answers.
- Which callback runs when the activity becomes fully interactive? Answer: onResume.
- Where is data saved before possible destruction? Answer: onSaveInstanceState(Bundle).
2. Creating multiple activities
Plain-language definition and why it matters. Real apps have multiple screens; each screen is typically an Activity (e.g., Login, Home, Profile, Settings). Creating multiple activities lets users navigate between screens.
Core theory. Each activity: Kotlin class extending AppCompatActivity, its own layout XML (setContentView), registered in AndroidManifest.xml with <activity android:name=".ClassName" />. Navigate between them using Intents. The launcher activity has an intent filter with MAIN action and LAUNCHER category.
Syntax / notation. Manifest:
<activity android:name=".ProfileActivity" android:exported="false" />
Worked example. Two-screen app: MainActivity (login) and HomeActivity.
- MainActivity layout has a Button "Go to Home".
- Button click:
val i = Intent(this, HomeActivity::class.java); startActivity(i). - HomeActivity:
setContentView(R.layout.activity_home)with a welcome TextView. - Both declared in manifest; MainActivity has LAUNCHER intent filter.
Realistic use case. An e-commerce app: ProductListActivity → ProductDetailActivity → CheckoutActivity.
Common mistakes / limitations. Forgetting manifest registration (ActivityNotFoundException); too many activities for simple navigation (consider fragments); not finishing sensitive activities (security).
Exam-ready answer points. Steps to create multiple activities; manifest registration; launcher intent filter; navigating with Intent.
Self-check questions with answers.
- Which manifest element registers an activity? Answer:
<activity>. - Which activity is the app entry point? Answer: the one with MAIN/LAUNCHER intent filter.
3. Declaring activities in the manifest
Plain-language definition and why it matters. The manifest tells the Android system about every component (activity, service, receiver, provider) and required permissions. Unregistered activities cannot be launched.
Core theory. <application> contains <activity android:name=".MainActivity" ...> with optional android:label, android:icon, android:theme, android:exported (whether other apps can start it, required for Android 12+), android:screenOrientation, android:windowSoftInputMode. The launcher activity includes <intent-filter> with <action android:name="android.intent.action.MAIN"/> and <category android:name="android.intent.category.LAUNCHER"/>.
Syntax / notation.
<activity android:name=".SettingsActivity"
android:exported="false"
android:label="@string/settings" />
Worked example. Declare SettingsActivity as non-exported with a label; MainActivity as launcher:
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
Realistic use case. A payment activity handling internal logic is set exported="false" so other apps can't invoke it.
Common mistakes / limitations. Missing exported attribute on Android 12+ (build error); wrong class name (crash); declaring every screen as launcher.
Exam-ready answer points. Explain manifest activity declaration; list attributes (name, exported, label, theme); explain intent filter for launcher.
Self-check questions with answers.
- What happens if an activity is not declared in the manifest? Answer: launching it throws ActivityNotFoundException.
- Which attribute controls whether other apps can start an activity? Answer:
android:exported.
4. Connecting activities with intents
Plain-language definition and why it matters. An Intent is a messaging object used to request an action from another component (usually to start an Activity). It matters because intents are the primary way activities communicate and navigate.
Core theory. Explicit intent names the target component: Intent(this, TargetActivity::class.java). Implicit intent names an action (e.g., ACTION_VIEW, ACTION_SEND) and the system resolves an app. startActivity(intent) starts; startActivityForResult / ActivityResult APIs get a result back. Flags like FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOP manage the back stack.
Syntax / notation.
val intent = Intent(this, DetailActivity::class.java)
startActivity(intent)
Worked example. From MainActivity, open DetailActivity on button click:
button.setOnClickListener {
startActivity(Intent(this, DetailActivity::class.java))
}
Implicit example: open a web page:
startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://example.com")))
Realistic use case. A "Share" button uses implicit ACTION_SEND intent to let the user pick any installed app (WhatsApp, email, SMS).
Comparison table.
| Intent type | Target specified? | Example |
|---|---|---|
| Explicit | yes, by class | start another activity in your app |
| Implicit | no, by action | open web page, share text |
Common mistakes / limitations. Implicit intent with no app to handle it (crash unless wrapped in resolveActivity check); forgetting startActivity.
Exam-ready answer points. Define Intent; contrast explicit vs implicit; show startActivity syntax; mention intent flags/resolveActivity.
Self-check questions with answers.
- Difference between explicit and implicit intent? Answer: explicit names the component; implicit names an action.
- Method to start an activity? Answer:
startActivity(intent).
5. Passing data between activities
Plain-language definition and why it matters. Data (text, numbers, objects) travels with an intent so the next activity can show or use it. It matters because screens often need context from the previous screen (e.g., selected product ID).
Core theory. Use intent extras: intent.putExtra("key", value) before startActivity; retrieve in target with intent.getStringExtra("key"), getIntExtra, etc. Parcelable/Serializable for objects. Provide default values for get*Extra to avoid nulls. For large data, use a database or shared ViewModel instead.
Syntax / notation.
intent.putExtra("product_id", 101)
// target:
val id = intent.getIntExtra("product_id", -1)
Worked example. Product list → detail:
- MainActivity:
intent.putExtra("product_name", "Apple"),putExtra("price", 120). - DetailActivity:
val name = intent.getStringExtra("product_name") ?: "Unknown",val price = intent.getIntExtra("price", 0); display in TextViews.
Realistic use case. A contact app passes the selected contact's ID from ContactsActivity to ContactDetailActivity to fetch and show details.
Comparison table.
| Method | Data size | Best for |
|---|---|---|
| Intent extras | small (text, int, Parcelable) | passing data between activities |
| Database | large | shared persistent data |
| ViewModel | medium | fragments/activities in same task |
Common mistakes / limitations. Reading a missing extra without default (null crash); putting non-Parcelable objects in extras; size limits on intents (don't pass bitmaps/lists).
Exam-ready answer points. Explain putExtra/getExtra; list types (String, Int, Parcelable); mention defaults and size limits.
Self-check questions with answers.
- How do you send a string to another activity? Answer:
intent.putExtra("key", value). - How does the target read it? Answer:
intent.getStringExtra("key").
6. Getting a result back from a child activity
Plain-language definition and why it matters. A child activity can return data to its parent (e.g., user picks a date or image). It matters for flows like "pick contact" or "capture photo then return."
Core theory. Modern API: Activity Result APIs (registerForActivityLauncher). Parent launches with startForResult(intent) and provides a callback receiving resultCode (RESULT_OK/RESULT_CANCELED) and data intent. Older: startActivityForResult(intent, requestCode) + onActivityResult(requestCode, resultCode, data). Child sets result with setResult(RESULT_OK, data) then finish().
Syntax / notation.
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val data = result.data
}
}
launcher.launch(Intent(this, PickerActivity::class.java))
Worked example. Pick a color:
- MainActivity launches ColorPickerActivity.
- ColorPickerActivity user selects "Green", calls
setResult(RESULT_OK, Intent().putExtra("color", "Green")),finish(). - MainActivity callback reads
data.getStringExtra("color")and updates a TextView.
Realistic use case. Camera capture: app launches camera activity, gets back the photo URI in the result.
Comparison table.
| Approach | API | requestCode needed? |
|---|---|---|
| Modern | Activity Result APIs | no |
| Legacy | startActivityForResult/onActivityResult | yes |
Common mistakes / limitations. Forgetting to check resultCode == RESULT_OK; not calling setResult/finish in child; using wrong requestCode in legacy approach.
Exam-ready answer points. Explain getting a result back; name Activity Result APIs and legacy method; explain RESULT_OK/RESULT_CANCELED and setResult.
Self-check questions with answers.
- Which result code means success? Answer: RESULT_OK.
- Modern replacement for startActivityForResult? Answer: Activity Result APIs / registerForActivityResult.
7. Getting and setting data to/from the layout file
Plain-language definition and why it matters. Layout data means reading user input from widgets (EditText, CheckBox, Spinner) and setting text/images on widgets (TextView, ImageView) from code. It matters because the UI must reflect program state and user input.
Core theory. Use findViewById<EditText>(R.id.email) (Kotlin) or ViewBinding (binding.email.text). Set text: textView.text = "Hello"; read: val email = editText.text.toString(). CheckBox: isChecked; RadioButton: radioGroup.checkedRadioButtonId; Spinner: selectedItem. ViewBinding generates a binding class so findViewById is unnecessary and type-safe.
Syntax / notation. ViewBinding:
private lateinit var binding: ActivityMainBinding
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.welcomeText.text = "Hello"
Worked example. Read form and show result:
- Layout: EditText
nameInput, ButtonshowBtn, TextViewresultText. - Button click:
val name = binding.nameInput.text.toString(); binding.resultText.text = "Hello, $name".
Realistic use case. A calculator reads two EditTexts, computes, and writes the result to a TextView.
Comparison table.
| Technique | Pros | Cons |
|---|---|---|
| findViewById | built-in | verbose, nullable, runtime cast |
| ViewBinding | type-safe, null-safe, concise | generated class per layout |
Common mistakes / limitations. Accessing views before setContentView/inflate (null); reading EditText before user types (empty string); memory leak if binding held after destroy.
Exam-ready answer points. Explain reading/setting widget data; show findViewById and ViewBinding; name widget state properties (text, isChecked).
Self-check questions with answers.
- How do you read an EditText's text? Answer:
editText.text.toString(). - What is ViewBinding? Answer: a type-safe generated class to access views without findViewById.
Key terms — Unit 4
Activity · life cycle · onCreate/onStart/onResume/onPause/onStop/onDestroy · onSaveInstanceState · Intent · explicit/implicit intent · Intent extra · Activity Result APIs · setResult · findViewById · ViewBinding · manifest · activity tag
Unit summary — Unit 4
Activities are screens managed by a life cycle (onCreate…onDestroy); multiple activities are declared in the manifest (launcher activity has MAIN/LAUNCHER filter); Intents connect activities and carry extras; results come back via Activity Result APIs; layout data is read/set via findViewById or ViewBinding.
Unit 5: UI Fragments, Menus and Dialogs
Teaching hours: 6
Topics in outline order
- The need for UI flexibility, Introduction to fragments, Lifecycle of fragment, Creating a UI fragment, Creating a fragment class, Wiring widgets in fragment, Introduction to fragment manager, Difference between Activity and Fragments
- Menus (Introduction, Types, Implementing menu in an application)
- Dialogs (Introduction, Creating a dialog fragment, Setting a dialog's content)
1. The need for UI flexibility, Introduction to fragments, Lifecycle of fragment, Creating a UI fragment, Creating a fragment class, Wiring widgets in fragment, Introduction to fragment manager, Difference between Activity and Fragments
Plain-language definition and why it matters. A Fragment is a modular piece of an activity's UI with its own life cycle. Fragments matter because they let one activity show different panels (e.g., list + detail on tablets) and reuse UI across screens, providing UI flexibility for different screen sizes.
Core theory. Fragment life cycle: onAttach, onCreate, onCreateView (inflate layout, return root view), onViewCreated, onStart, onResume, onPause, onStop, onDestroyView, onDestroy, onDetach. Creating a fragment: Kotlin class extending Fragment, override onCreateView with inflater.inflate(R.layout.fragment_xxx, container, false). Wiring widgets: view.findViewById or ViewBinding in onViewCreated. FragmentManager: supportFragmentManager handles transactions — beginTransaction().replace(R.id.container, fragment).commit(). Difference: an Activity is a full screen/app entry point; a Fragment lives inside an activity and cannot exist alone; multiple fragments can compose one activity.
Syntax / notation.
class ItemFragment : Fragment() {
private lateinit var binding: FragmentItemBinding
override fun onCreateView(inflater, container, savedInstanceState): View {
binding = FragmentItemBinding.inflate(inflater, container, false)
return binding.root
}
}
// transaction
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, ItemFragment())
.commit()
Worked example. Master-detail on tablet:
activity_main.xml: FrameLayout containerfragment_container.ItemListFragmentshows list;ItemDetailFragmentshows detail.- On phone: replace container with DetailFragment on item click (separate screens).
- On tablet: both fragments side by side in one activity.
Realistic use case. An email app: list fragment left, message fragment right on tablets; single-fragment activities on phones.
Comparison table.
| Activity | Fragment | |
|---|---|---|
| Can exist alone | yes | no (hosted in activity) |
| Life cycle | own | own, tied to host |
| UI role | full screen | reusable panel |
| Navigation | intent between | transaction within activity |
Common mistakes / limitations. Inflating fragment layout with attachToRoot=true (must be false); fragment transactions not committed; losing fragment state on rotation (use ViewModel or retained instance); nested fragment manager confusion.
Exam-ready answer points. Explain need for fragments; list fragment life cycle; show creation and FragmentManager transaction; contrast Activity vs Fragment.
Self-check questions with answers.
- Why use fragments? Answer: UI flexibility, reuse, multi-pane layouts (especially tablets).
- Which class manages fragment transactions? Answer: FragmentManager (supportFragmentManager).
2. Menus (Introduction, Types, Implementing menu in an application)
Plain-language definition and why it matters. Menus provide user actions (settings, search, help) without cluttering the main screen. They matter for secondary actions and app-wide commands.
Core theory. Types: Options Menu (top/toolbar, onCreateOptionsMenu), Context Menu (long-register view), Popup Menu (anchored to a view). Menu XML in res/menu/ with <item android:id android:title android:showAsAction="ifRoom|never"/>. Handle clicks in onOptionsItemSelected(item). showAsAction="ifRoom" shows in toolbar if space; otherwise in overflow.
Syntax / notation. res/menu/main_menu.xml:
<menu>
<item android:id="@+id/action_settings"
android:title="@string/settings"
app:showAsAction="never"/>
</menu>
Kotlin:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> { startSettings(); true }
else -> super.onOptionsItemSelected(item)
}
}
Worked example. Add Settings and Help to toolbar:
- menu XML with two items.
onCreateOptionsMenuinflatesR.menu.main_menu.- Click opens SettingsActivity or shows a Help dialog.
Realistic use case. A settings option in the overflow menu opens the preferences screen.
Comparison table.
| Menu type | Trigger | Location |
|---|---|---|
| Options menu | menu button/toolbar | top app bar |
| Context menu | long press | floating over a view |
| Popup menu | programmatic | anchored to a view |
Common mistakes / limitations. Forgetting onCreateOptionsMenu inflation (menu empty); wrong itemId in switch; not returning true when an item is handled.
Exam-ready answer points. Define menu; list types; show menu XML and onOptionsItemSelected; explain showAsAction.
Self-check questions with answers.
- Where is menu XML stored? Answer: res/menu/.
- Which callback inflates the options menu? Answer: onCreateOptionsMenu.
3. Dialogs (Introduction, Creating a dialog fragment, Setting a dialog's content)
Plain-language definition and why it matters. A dialog is a small floating window that prompts the user or collects input without leaving the current screen. Dialogs matter for confirmations, alerts, and short forms.
Core theory. Dialog types: AlertDialog (title, message, buttons), DialogFragment (a fragment showing a dialog, survives rotation), custom dialogs via Dialog with custom layout. AlertDialog.Builder builds with setTitle, setMessage, setPositiveButton, setNegativeButton, setNeutralButton. DialogFragment: class extending DialogFragment, override onCreateDialog returning an AlertDialog, shown via show(supportFragmentManager, "tag").
Syntax / notation.
val dialog = AlertDialog.Builder(this)
.setTitle("Confirm")
.setMessage("Delete item?")
.setPositiveButton("Delete") { _, _ -> delete() }
.setNegativeButton("Cancel") { _, _ -> }
.create()
dialog.show()
Worked example. Delete confirmation:
- User taps Delete → show AlertDialog with Delete/Cancel.
- Delete click → remove item from list, refresh; Cancel → dismiss.
Realistic use case. Before logging out, app shows "Are you sure?" dialog with Yes/No.
Comparison table.
| Dialog | Use |
|---|---|
| AlertDialog | simple alerts/confirmations |
| DialogFragment | dialog that survives config changes |
| Custom dialog | custom layout/form |
Common mistakes / limitations. Using plain Dialog (lost on rotation) instead of DialogFragment; not handling button clicks; blocking UI with long work inside a dialog.
Exam-ready answer points. Define dialog; explain AlertDialog.Builder and DialogFragment; show button handlers.
Self-check questions with answers.
- Which dialog class survives screen rotation? Answer: DialogFragment.
- Which builder creates alert dialogs? Answer: AlertDialog.Builder.
Key terms — Unit 5
Fragment · fragment life cycle · FragmentManager · fragment transaction · replace/commit · Activity vs Fragment · Options menu · Context menu · Popup menu · onCreateOptionsMenu · onOptionsItemSelected · Dialog · AlertDialog · DialogFragment
Unit summary — Unit 5
Fragments provide flexible, reusable UI panels within an activity (managed by FragmentManager transactions). Menus (options/context/popup) expose secondary actions via res/menu XML. Dialogs (AlertDialog, DialogFragment) prompt users without leaving the screen; DialogFragment survives rotation.
Unit 6: Listview, Gridview and Recyclerview
Teaching hours: 6
Topics in outline order
- Listview (Introduction, Features, Implementing listview in an application)
- Gridview (Introduction, Features, Implementing gridview in an application)
- Recyclerview (Introduction, Features, Implementing recyclerview in an application)
1. Listview (Introduction, Features, Implementing listview in an application)
Plain-language definition and why it matters. ListView shows a scrollable single-column list of items. It matters because lists (contacts, messages, settings) are among the most common mobile UI patterns.
Core theory. ListView uses an Adapter (ArrayAdapter, SimpleCursorAdapter, or custom BaseAdapter) to bind data to rows. Each row is a view; setAdapter connects data to the list. setOnItemClickListener handles taps. ListView recycles rows via convertView (older pattern). Attributes: android:entries (for arrays), divider, dividerHeight.
Syntax / notation.
val listView: ListView = findViewById(R.id.list)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
listView.adapter = adapter
listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
val selected = items[position]
}
Worked example. To-do list:
items = arrayOf("Buy milk", "Call mom", "Study").- ArrayAdapter with
simple_list_item_1. - Click shows a Toast with the selected item.
Realistic use case. A contacts app shows the contact list in a ListView; tapping a contact opens details.
Comparison table.
| View | Columns | Modern? | Adapter needed |
|---|---|---|---|
| ListView | single | legacy (replaced by RecyclerView) | yes |
| GridView | grid | legacy | yes |
| RecyclerView | flexible | recommended | yes |
Swipe to see all columns
Common mistakes / limitations. Not using an adapter (empty list); long row layouts slow scrolling; ListView is outdated — prefer RecyclerView for new apps.
Exam-ready answer points. Define ListView; explain adapter role; show ArrayAdapter setup and item click; mention limitations.
Self-check questions with answers.
- What binds data to a ListView? Answer: an Adapter (e.g., ArrayAdapter).
- Which listener handles ListView item taps? Answer: OnItemClickListener.
2. Gridview (Introduction, Features, Implementing gridview in an application)
Plain-language definition and why it matters. GridView shows items in a two-dimensional, scrollable grid. It matters for galleries, photo grids, and dashboards where items are better arranged in rows and columns.
Core theory. Like ListView but with android:numColumns (integer or auto_fit), android:verticalSpacing, android:horizontalSpacing, android:columnWidth. Uses an Adapter (often image adapter). setOnItemClickListener handles taps. Good for uniform-sized items (thumbnails).
Syntax / notation.
<GridView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="100dp" />
Worked example. Image gallery:
- Adapter loads thumbnail drawables into
ImageViewrows. - GridView
numColumns="auto_fit",columnWidth="120dp". - Click shows the full image.
Realistic use case. A photo app displays the camera roll as a grid of thumbnails.
Common mistakes / limitations. Large bitmaps in grid cells cause OutOfMemoryError (use libraries like Glide/Coil or downsample); GridView is legacy (RecyclerView with GridLayoutManager preferred).
Exam-ready answer points. Define GridView; list grid attributes (numColumns, columnWidth, spacing); explain adapter use; mention image loading caution.
Self-check questions with answers.
- Which attribute sets the number of columns? Answer:
android:numColumns. - What is GridView best for? Answer: uniform items in a grid (e.g., photo gallery).
3. Recyclerview (Introduction, Features, Implementing recyclerview in an application)
Plain-language definition and why it matters. RecyclerView is the modern, flexible replacement for ListView/GridView, showing large scrollable lists/grids with efficient view recycling. It matters because it handles large data sets smoothly and supports many layouts.
Core theory. Components: RecyclerView (the view), LayoutManager (LinearLayoutManager for list, GridLayoutManager for grid, StaggeredGridLayoutManager), Adapter (extends RecyclerView.Adapter<ViewHolder>), ViewHolder (holds row views). onCreateViewHolder inflates row layout; onBindViewHolder binds data to position; getItemCount returns size. DiffUtil for efficient updates. notifyDataSetChanged() refreshes. More boilerplate than ListView but far more efficient and flexible.
Syntax / notation.
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = MyAdapter(items)
// Adapter
class MyAdapter(private val items: List<String>) :
RecyclerView.Adapter<MyAdapter.ViewHolder>() {
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent, viewType): ViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.row_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder, position) {
holder.view.findViewById<TextView>(R.id.text).text = items[position]
}
override fun getItemCount() = items.size
}
Worked example. Product list:
- RecyclerView with LinearLayoutManager vertical.
- Adapter binds product name/price to each row.
- Click opens product detail via listener callback.
Realistic use case. A social feed with hundreds of posts uses RecyclerView for smooth scrolling and view recycling.
Comparison table.
| Feature | ListView/GridView | RecyclerView |
|---|---|---|
| View recycling | basic convertView | ViewHolder (required) |
| Layouts | list or grid | list/grid/staggered via LayoutManager |
| Performance | lower for large data | high |
| Recommendation | legacy | preferred |
Common mistakes / limitations. Forgetting setLayoutManager (crash: RecyclerView has no LayoutManager); not implementing ViewHolder correctly; calling notifyDataSetChanged() too often (use DiffUtil for partial updates).
Exam-ready answer points. Define RecyclerView; list components (LayoutManager, Adapter, ViewHolder); contrast with ListView; show adapter methods.
Self-check questions with answers.
- Name the three main RecyclerView components. Answer: RecyclerView, LayoutManager, Adapter (and ViewHolder).
- What crash happens without a LayoutManager? Answer: "RecyclerView has no LayoutManager".
Key terms — Unit 6
ListView · GridView · RecyclerView · Adapter · ViewHolder · LayoutManager · LinearLayoutManager · GridLayoutManager · OnItemClickListener · DiffUtil · notifyDataSetChanged · convertView
Unit summary — Unit 6
ListView and GridView are legacy adapter views for single-column lists and grids. RecyclerView is the modern replacement using LayoutManager + Adapter + ViewHolder for efficient scrolling of lists, grids, and staggered layouts.
Unit 7: Advanced Android Concepts
Teaching hours: 10
Topics in outline order
- Local database with SQLite (Establishing connection, creating database and tables, data manipulation)
- Introduction to API
- API Types
- Introduction to JSON
- Retrieving contents from remote server
- Sending contents to remote server
- Implementing Google Maps in android application
- Procedure for publishing application on Google Play Store
1. Local database with SQLite (Establishing connection, creating database and tables, data manipulation)
Plain-language definition and why it matters. SQLite is a file-based relational database stored on the device, used for local data (notes, settings, cached content). It matters because apps often need offline storage and structured queries without a network.
Core theory. Android SQLite via android.database.sqlite.SQLiteOpenHelper: subclass, override onCreate(db) (create tables with CREATE TABLE) and onUpgrade(db, oldVersion, newVersion) (ALTER/DROP). Get writable/readable database (getWritableDatabase(), getReadableDatabase()). Manipulate data with db.insert, db.update, db.delete, db.query, or rawQuery("SELECT ..."). Use ContentValues for insert/update rows. Always close cursor/database or use try-with-resources. SQL injection risk with string concatenation — use parameterized ? bindings.
Syntax / notation.
class AppDbHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, VERSION) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, body TEXT)")
}
override fun onUpgrade(db, oldV, newV) {
db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db)
}
}
Insert: val cv = ContentValues(); cv.put("title","x"); db.insert("notes", null, cv)
Query: db.query("notes", arrayOf("id","title"), null, null, null, null, null)
Worked example. Notes app:
onCreatecreatesnotes(id, title, body).- Add note: ContentValues, insert.
- List notes: query, move cursor, read columns.
- Delete note:
db.delete("notes", "id=?", arrayOf(id.toString())).
Realistic use case. A diary app stores entries locally in SQLite so they're available offline.
Comparison table.
| Operation | Method | Example |
|---|---|---|
| Create table | execSQL(CREATE TABLE) | schema |
| Insert | insert(table, null, values) | ContentValues |
| Read | query(...) or rawQuery | Cursor |
| Update | update(table, values, whereClause, whereArgs) | ContentValues |
| Delete | delete(table, whereClause, whereArgs) | row removal |
Common mistakes / limitations. Not calling onUpgrade logic (schema changes lost); raw SQL string concatenation → injection; forgetting to close Cursor; main-thread database access blocks UI (use a background thread/coroutine or Room).
Exam-ready answer points. Explain SQLiteOpenHelper (onCreate/onUpgrade); show CREATE TABLE; explain insert/update/delete/query with ContentValues and Cursor; mention parameterized queries.
Self-check questions with answers.
- Which class manages SQLite creation/upgrade? Answer: SQLiteOpenHelper.
- Which method creates tables? Answer: onCreate (execSQL CREATE TABLE).
2. Introduction to API
Plain-language definition and why it matters. An API (Application Programming Interface) lets one app request data or actions from another service (often over HTTP). It matters because mobile apps commonly fetch remote data (weather, news, prices) instead of storing everything locally.
Core theory. Web API: client sends an HTTP request (GET, POST, PUT, DELETE) to a URL (endpoint); server returns a response (status code + body, often JSON). Base URL + path = endpoint. Query parameters (?key=value) and path parameters. Headers (Content-Type, Authorization). Common status codes: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error. Android networking libraries: HttpURLConnection, OkHttp, Retrofit, Volley. Network must run off the main thread (coroutines, RxJava, callbacks).
Syntax / notation. HTTP request:
GET https://api.example.com/v1/items?limit=10
Response (JSON): [{"id":1,"name":"Item"}] with status 200.
Worked example. Fetch public holidays:
- Endpoint
GET https://date.nager.at/api/v3/publicholidays/2024/NPreturns JSON list. - App calls via Retrofit/coroutine, parses JSON, shows list.
- Network call in a coroutine (Dispatchers.IO), result updated on Main.
Realistic use case. A weather app calls a weather API with the user's city and displays temperature.
Comparison table.
| Method | Use | Body? |
|---|---|---|
| GET | fetch data | no |
| POST | create/submit | yes |
| PUT | update | yes |
| DELETE | remove | no |
Common mistakes / limitations. Networking on main thread (NetworkOnMainThreadException); forgetting INTERNET permission; not handling no-internet; ignoring error status codes.
Exam-ready answer points. Define API/endpoint; list HTTP methods and status codes; explain client-server request/response; mention main-thread restriction.
Self-check questions with answers.
- Which HTTP method fetches data? Answer: GET.
- Why must API calls run off the main thread? Answer: to avoid blocking the UI (NetworkOnMainThreadException).
3. API Types
Plain-language definition and why it matters. API types differ in architecture and data format; choosing the right one affects coupling, performance, and ease of use. Common types: REST, SOAP, GraphQL, and local/internal vs public/private APIs.
Core theory. REST (Representational State Transfer): resource-based, stateless, uses HTTP methods and URLs, usually JSON — most common for mobile. SOAP: XML-based, strict envelope/WS standards, heavier, used in enterprise/legacy. GraphQL: client queries exactly the fields it needs via a single endpoint (flexible, fewer round trips). Public API: open to developers (often with API key); Private API: internal to an organization. Open API vs partner API.
Syntax / notation. REST: GET /users/123. GraphQL: POST /graphql body { user(id:123){ name email } }. SOAP: XML envelope with <Body>.
Worked example. Mobile app needs user name+email only: REST returns full user object (over-fetching); GraphQL requests { name email }, returning only those fields — less data on mobile networks.
Realistic use case. A Nepali bank uses SOAP internally (legacy) but exposes a REST API to its mobile app customers.
Comparison table.
| Type | Format | Style | Typical use |
|---|---|---|---|
| REST | JSON | HTTP resources | mobile/web APIs |
| SOAP | XML | envelope/contract | enterprise, banking |
| GraphQL | JSON | query language | flexible client data needs |
Swipe to see all columns
Common mistakes / limitations. Treating all APIs as REST; assuming GraphQL is always better (caching harder); ignoring API versioning and rate limits.
Exam-ready answer points. Compare REST, SOAP, GraphQL; explain public vs private; give mobile relevance.
Self-check questions with answers.
- Which API type is most common for mobile? Answer: REST.
- Which API lets the client request specific fields? Answer: GraphQL.
4. Introduction to JSON
Plain-language definition and why it matters. JSON (JavaScript Object Notation) is a lightweight text format for data interchange, the most common API response format. It matters because mobile apps parse JSON to show server data.
Core theory. JSON structures: objects {} with key/value pairs, arrays [] of values, strings (double quotes), numbers, booleans (true/false), null. Keys must be strings; values can be any type including nested objects/arrays. Example: {"id":1,"name":"Sita","active":true,"tags":["a","b"]}. Android parsing: org.json.JSONObject/JSONArray, Gson, Moshi, kotlinx.serialization. Convert JSON string → Kotlin data class (deserialization), and object → JSON (serialization).
Syntax / notation.
{"items":[{"id":1,"title":"Buy milk"},{"id":2,"title":"Call mom"}]}
Kotlin data class:
data class Item(val id: Int, val title: String)
Worked example. Parse a JSON list:
- String:
[{"id":1,"title":"A"},{"id":2,"title":"B"}]. val array = JSONArray(jsonString); looparray.getJSONObject(i).getString("title").- Or Gson:
gson.fromJson(json, TypeToken<List<Item>>(){}.type).
Realistic use case. A news app receives a JSON array of articles from the API and renders each title.
Comparison table.
| JSON type | Syntax | Example |
|---|---|---|
| object | {} |
{"name":"Sita"} |
| array | [] |
["a","b"] |
| string | " " |
"Nepal" |
| number | digits | 42 |
| boolean | true/false | true |
| null | null |
null |
Common mistakes / limitations. Using single quotes (invalid JSON); trailing commas (invalid); mismatched types when parsing (exception); escaping quotes inside strings (\").
Exam-ready answer points. Define JSON; list value types with syntax; show object/array example; explain parsing in Android (JSONObject/Gson).
Self-check questions with answers.
- What character begins a JSON object? Answer:
{. - How are JSON strings quoted? Answer: double quotes
".
5. Retrieving contents from remote server
Plain-language definition and why it matters. Retrieving contents means downloading data (text, JSON, images) from a remote server to display in the app. It matters for fresh, server-driven content (news, prices, profiles).
Core theory. Steps: build request URL (endpoint + parameters), choose HTTP client, execute GET off the main thread (coroutine/OkHttp/Retrofit/Volley), read response body, parse JSON, update UI on main thread. Handle loading state, success, error, and no-network. Use timeouts and caching (ETag/Cache-Control). Images: load with Coil/Glide/Picasso into ImageView (handles caching and memory).
Syntax / notation. Kotlin coroutine with Retrofit:
viewModelScope.launch {
val response = apiService.getItems()
if (response.isSuccessful) _items.value = response.body()
else _error.value = "Failed ${response.code}"
}
Worked example. Fetch news:
- GET
https://newsapi.example.com/articles(with API key header). - Show loading spinner → parse JSON list → show in RecyclerView → hide spinner; on error show "Try again".
Realistic use case. A stock app fetches latest prices every few minutes and updates the list.
Comparison table.
| State | UI action |
|---|---|
| loading | show spinner/skeleton |
| success | show data |
| error | show message + retry |
| empty | show "no data" |
Common mistakes / limitations. Updating UI from a background thread (crash); not showing loading state (app seems frozen); unbounded image memory use; no retry on failure.
Exam-ready answer points. Explain retrieval steps; state main-thread UI update rule; list loading/success/error handling; mention image-loading libraries.
Self-check questions with answers.
- Where must UI updates happen? Answer: on the main thread.
- Which state should be shown while fetching? Answer: loading/spinner.
6. Sending contents to remote server
Plain-language definition and why it matters. Sending contents means uploading user data (form submissions, photos, profile updates) to a server. It matters for user-generated content and syncing.
Core theory. Usually POST (create) or PUT (update) with a body (JSON or multipart for files). Steps: build object, serialize to JSON (Gson/kotlinx.serialization), set Content-Type: application/json, send off main thread, read response status/body, handle success/error. For files: multipart request with parts (fields + file). Auth: send token in Authorization: Bearer <token> header. Validate input before sending; show progress.
Syntax / notation. Retrofit POST:
@POST("users") suspend fun createUser(@Body user: User): Response<User>
Multipart (file): @Part file: MultipartBody.Part.
Worked example. Register user:
- Build
User(name, email, password), serialize to JSON. - POST to
/register; on 201 save token; on 400 show validation errors.
Realistic use case. A profile screen lets the user upload a profile picture (multipart) and update display name (JSON).
Comparison table.
| Method | Body | Typical use |
|---|---|---|
| POST | JSON/multipart | create resource, submit form |
| PUT | JSON | update existing resource |
| PATCH | JSON | partial update |
Common mistakes / limitations. Sending sensitive data over HTTP (not HTTPS) — expose; large files without progress/cancellation; not handling 401 (token expired); sending bitmaps directly in JSON (use multipart/upload URL).
Exam-ready answer points. Explain sending via POST/PUT; JSON serialization; auth header; multipart for files; main-thread rule and error handling.
Self-check questions with answers.
- Which HTTP method creates a resource? Answer: POST.
- How are files usually sent? Answer: multipart request.
7. Implementing Google Maps in android application
Plain-language definition and why it matters. Google Maps embeds an interactive map (markers, camera, routes, places) in an Android app. It matters for location-based apps (delivery, travel, find-nearby).
Core theory. Requirements: Google Cloud project, Maps SDK for Android API key (restricted to app package/SHA-1), com.google.android.gms:play-services-maps dependency, android.permission.ACCESS_FINE_LOCATION/COARSE_LOCATION, meta-data in manifest (com.google.android.geo.API_KEY). Layout: com.google.android.gms.maps.MapView or MapFragment/SupportMapFragment. Code: getMapAsync(OnMapReadyCallback) → GoogleMap object; add markers (addMarker(MarkerOptions().position(latLng).title("x"))), move camera (moveCamera(CameraUpdateFactory.newLatLngZoom)), enable location layer. Handle permissions at runtime (Android 6+).
Syntax / notation.
<fragment android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map" ... />
Manifest: <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_KEY"/>
Worked example. Show Kathmandu:
- LatLng(27.7172, 85.3240).
map.addMarker(MarkerOptions().position(kathmandu).title("Kathmandu")).map.moveCamera(CameraUpdateFactory.newLatLngZoom(kathmandu, 12f)).
Realistic use case. A food-delivery app shows the restaurant and user on a map.
Common mistakes / limitations. Missing/restricted API key (map shows blank/grid); not requesting location permission (location layer fails); API key not restricted (security/cost); Maps SDK not enabled in Cloud Console.
Exam-ready answer points. List requirements (API key, dependency, permissions, meta-data); show adding a marker and moving camera; explain runtime location permission.
Self-check questions with answers.
- What is required to display Google Maps? Answer: an API key from Google Cloud and the Maps dependency.
- Which class is the map object in code? Answer: GoogleMap.
8. Procedure for publishing application on Google Play Store
Plain-language definition and why it matters. Publishing makes the app available to users via the Play Store. It matters because development ends only when users can install the app.
Core theory. Steps: build a signed release AAB/APK (generate upload keystore with keytool, configure signingConfigs in build.gradle, Build → Generate Signed Bundle/APK); set versionCode/versionName; test on real devices; create Google Play Console account (one-time fee); create app, set package name, title, description, screenshots, icons, privacy policy; content rating; upload AAB to internal/closed/open track; review and publish; manage updates (increment versionCode). Play App Signing (Google manages the upload key). Optimize size (Android App Bundle, delivery by device config).
Syntax / notation. keytool:
keytool -genkeypair -v -keystore upload-keystore.jks -keyalg RSA -keysize 2048 -validity 10000 -alias upload
Worked example. Release build:
keytoolcreatesupload-keystore.jks.- build.gradle signingConfigs release with storeFile/password/alias.
- Build → Generate Signed Bundle →
app-release.aab. - Upload to Play Console, select production track, roll out.
Realistic use case. A student publishes their final-year project app so friends can install it.
Common mistakes / limitations. Debug APK cannot be published (must be signed release); versionCode not incremented (update rejected); missing privacy policy (rejection); wrong package name collisions; testing only on emulator.
Exam-ready answer points. List publishing steps; explain signed AAB/APK and keystore; explain Play Console tracks and versionCode; mention review and updates.
Self-check questions with answers.
- Which file format is preferred for Play Store publishing? Answer: Android App Bundle (AAB).
- What must increase for each update? Answer: versionCode.
Key terms — Unit 7
SQLite · SQLiteOpenHelper · onCreate/onUpgrade · ContentValues · Cursor · API · endpoint · REST · SOAP · GraphQL · JSON · GET/POST/PUT/DELETE · Retrofit · coroutine · Google Maps · API key · MapFragment/SupportMapFragment · GoogleMap · marker · Play Store · AAB · versionCode · signing keystore
Unit summary — Unit 7
SQLite stores local structured data via SQLiteOpenHelper (insert/update/delete/query). APIs (REST most common) fetch/send remote data using HTTP methods and JSON off the main thread. Google Maps needs an API key, Maps dependency, permissions, and meta-data; markers and camera moves locate places. Publishing requires a signed release AAB, Play Console, versionCode increments, and store review.
Unit 8: Introduction to IOS Programming
Teaching hours: 18
Topics in outline order
- Introduction to ios and los programming, ios platform, Environment setup, Creating an Xcode project, Building the interface, Making connections, Running on the simulator
- Introduction to Swift language, Views and the view hierarchy, Storyboard and view controllers, working with widgets and its attributes, Creating a simple ios application
1. Introduction to ios and los programming, ios platform, Environment setup, Creating an Xcode project, Building the interface, Making connections, Running on the simulator
Plain-language definition and why it matters. iOS programming builds apps for Apple iPhone/iPad using Xcode on macOS. "los" in the source appears to be a typographical rendering of iOS. It matters because iOS is the second major mobile platform, with its own tools (Xcode), language (Swift), and distribution (App Store).
Core theory. iOS platform: closed ecosystem, Apple hardware (iPhone, iPad), iOS/iPadOS, App Store distribution with review. Environment: macOS required, Xcode (free from Mac App Store) includes IDE, Interface Builder, Simulator, Instruments. Apple ID for signing; paid Apple Developer Program ($99/yr) to publish on device/App Store. Creating an Xcode project: choose template (App), set product name, bundle identifier (com.example.app), interface (Storyboard or SwiftUI), language (Swift), save location. Building the interface: Interface Builder (storyboard/xib) drag-drop views, or SwiftUI code. Making connections: @IBOutlet (view to code), @IBAction (action/event to code) via Control-drag. Running on the simulator: choose device (iPhone 15, iPad), click Run; simulator mimics device but test on real iOS device before release.
Syntax / notation. Swift outlet/action:
@IBOutlet weak var label: UILabel!
@IBAction func buttonTapped(_ sender: UIButton) {
label.text = "Hello"
}
Worked example. Single-view app:
- Xcode → New → App, Swift, Storyboard.
- Main.storyboard: drag a Label and Button.
- Control-drag label →
@IBOutlet weak var greetingLabel. - Control-drag button →
@IBAction func sayHello. - Code:
greetingLabel.text = "Hello, iOS". - Run on iPhone 15 simulator → label updates on tap.
Realistic use case. A greeting app built once runs on iPhone and (with adaptations) iPad.
Comparison table.
| Android | iOS | |
|---|---|---|
| IDE | Android Studio | Xcode (macOS only) |
| Language | Kotlin/Java | Swift |
| Simulator | AVD | iOS Simulator |
| Distribution | Play Store | App Store |
| Bundle ID | package name | bundle identifier |
Common mistakes / limitations. Xcode needs macOS (not Windows/Linux); forgetting to set the bundle identifier; outlet not connected (nil crash at runtime); testing only on simulator (real-device differences).
Exam-ready answer points. Describe iOS platform and Xcode setup; list project creation steps; explain outlet/action connections; describe running on simulator.
Self-check questions with answers.
- Which IDE is used for iOS programming? Answer: Xcode.
- On which OS does Xcode run? Answer: macOS.
2. Introduction to Swift language, Views and the view hierarchy, Storyboard and view controllers, working with widgets and its attributes, Creating a simple ios application
Plain-language definition and why it matters. Swift is Apple's modern language for iOS/macOS apps; views form a hierarchy; storyboards and view controllers manage screens; widgets (UIButton, UILabel, UITextField, UISwitch, UISlider, UIImageView) have attributes. Together these let you build a complete simple iOS app.
Core theory. Swift: var/let, functions (func), optionals (String?, !, if let), classes/structs, closures. Views: UIView hierarchy; UIViewController manages a screen and its root view; UIView properties (frame, bounds, backgroundColor, alpha). Storyboard: visual file (.storyboard) with scenes (view controllers) and segues (transitions). View controller life cycle: viewDidLoad, viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear. Widgets/attributes: UILabel (text, font, textColor, alignment), UIButton (title, target-action), UITextField (text, placeholder, keyboardType), UISwitch (isOn), UIImageView (image, contentMode). Attributes set in Attributes Inspector or code.
Syntax / notation.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func showGreeting(_ sender: UIButton) {
let name = nameField.text ?? ""
resultLabel.text = "Hello, \(name)"
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Worked example. Simple iOS app (greeting):
- Storyboard: TextField, Button, Label.
- Outlets for field and label; action for button.
- On tap, read field text, set label "Hello, ".
- Run on simulator; type a name, tap, see greeting.
Realistic use case. A contact card app shows name/phone with editable fields.
Comparison table.
| Concept | iOS equivalent |
|---|---|
| Activity | UIViewController |
| layout XML | Storyboard / .xib / SwiftUI |
| findViewById | @IBOutlet |
| onClick | @IBAction / target-action |
| Intent | segue / UINavigationController push |
Common mistakes / limitations. Force-unwrapping a nil optional (!) crashes; outlet connected to wrong type; forgetting import UIKit; not embedding in UINavigationController for push navigation.
Exam-ready answer points. Explain Swift basics (optional, var/let); describe view hierarchy and UIViewController; explain storyboard, outlets, actions; list widget attributes; contrast with Android concepts.
Self-check questions with answers.
- Which Swift keyword declares a constant? Answer:
let. - Which iOS concept is similar to Android Activity? Answer: UIViewController.
Key terms — Unit 8
iOS · iPadOS · Xcode · macOS · Swift · bundle identifier · Storyboard · @IBOutlet · @IBAction · UIView · UIViewController · viewDidLoad · segue · UINavigationController · simulator · App Store
Unit summary — Unit 8
iOS programming uses Xcode on macOS and Swift; projects are created with a bundle identifier and built in Storyboard/SwiftUI; @IBOutlet/@IBAction connect interface to code; views form a hierarchy managed by UIViewController; apps run on the iOS Simulator and are distributed via the App Store.
Key terms (full course)
mobile device · platform · iOS · Android · native · cross-platform · API level · ART · SDK · AVD · emulator · Gradle · manifest · package name · view hierarchy · dp · sp · ConstraintLayout · widget · TextView · EditText · CheckBox · RadioButton · Spinner · OnClickListener · strings.xml · drawable · mipmap · adaptive icon · Activity · life cycle · Intent · explicit/implicit · Intent extra · Activity Result APIs · ViewBinding · Fragment · FragmentManager · Dialog · AlertDialog · DialogFragment · ListView · GridView · RecyclerView · Adapter · ViewHolder · LayoutManager · SQLite · SQLiteOpenHelper · API · REST · JSON · GET/POST · Google Maps · API key · AAB · versionCode · Xcode · Swift · Storyboard · @IBOutlet · @IBAction · UIViewController
Unit summary (full course)
Unit 1: mobile devices and mobile programming concepts. Unit 2: Android platform, setup, project creation, UI layout, classes, emulator. Unit 3: layout types, attributes, widgets, events, strings/colors/drawables, app icon. Unit 4: activity life cycle, multiple activities, intents, extras, results, layout data. Unit 5: fragments, menus, dialogs. Unit 6: ListView/GridView/RecyclerView. Unit 7: SQLite, APIs, JSON, remote data, Google Maps, Play Store publishing. Unit 8: iOS/Swift/Xcode and a simple iOS app.
Detailed practice questions and answer keys
-
List the five Android layout types and explain which is recommended for complex UIs and why. Answer: LinearLayout (row/column), RelativeLayout (relative positioning, legacy), TableLayout (rows/columns), AbsoluteLayout (fixed x,y, deprecated), ConstraintLayout (constraints, recommended). ConstraintLayout is recommended because it gives a flat view hierarchy and adapts to different screen sizes via constraints, guidelines, barriers, and chains.
-
Explain the Android activity life-cycle callbacks in order and how data survives screen rotation. Answer: onCreate → onStart → onResume → onPause → onStop → (onRestart) → onDestroy. Rotation destroys and recreates the activity; save data in
onSaveInstanceState(Bundle)and restore inonCreate/onRestoreInstanceState, or use ViewModel to survive process death. -
Write Kotlin code to pass a string from MainActivity to DetailActivity using an Intent, and read it in DetailActivity. Answer:
// MainActivity val intent = Intent(this, DetailActivity::class.java) intent.putExtra("message", "Hello") startActivity(intent) // DetailActivity val message = intent.getStringExtra("message") ?: "default" -
Describe how to implement a RecyclerView: name its main components and adapter methods. Answer: Components: RecyclerView, LayoutManager (LinearLayoutManager/GridLayoutManager), Adapter, ViewHolder. Adapter methods: onCreateViewHolder (inflate row), onBindViewHolder (bind data), getItemCount (size).
-
Explain SQLiteOpenHelper and show how to insert and query a row. Answer: Subclass SQLiteOpenHelper; override onCreate (CREATE TABLE via execSQL) and onUpgrade. Insert: ContentValues + db.insert(table, null, values). Query: db.query(...) returning a Cursor; move to first and read columns. Use parameterized
?to avoid injection. -
Contrast REST and GraphQL APIs, and explain why JSON is used. Answer: REST is resource-based over HTTP with standard methods (GET/POST) usually returning JSON; GraphQL lets clients request exactly the fields they need via one endpoint. JSON is a lightweight, language-independent text format (objects {}, arrays [], strings, numbers, booleans, null) used for API data interchange.
-
Outline the requirements to add Google Maps and the steps to publish on Play Store. Answer: Maps: Google Cloud API key (restricted), play-services-maps dependency, location permissions, manifest meta-data, SupportMapFragment/MapView, GoogleMap marker/camera. Play Store: signed release AAB (keystore via keytool), versionCode/versionName, Play Console account, app listing (description, screenshots, privacy policy), upload to track, review, publish; increment versionCode for updates.
-
Compare Android and iOS development (IDE, language, UI builder, distribution). Answer: Android: Android Studio, Kotlin/Java, XML layouts/Compose, Play Store. iOS: Xcode (macOS only), Swift, Storyboard/SwiftUI, App Store. Both use a simulator/emulator and require real-device testing before release.
References from the source syllabus
- TU document: https://portal.tu.edu.np/downloads/BCA_Syllabus-compressed_compre_2024_01_30_18_33_22.pdf
- Location: PDF p. 88-90
- Source file: the course outline
- SHA-256: sha256:0273e8e1e8b0094a9d669599fc4042914679523d3390539915dd9b2126ae0be3
- Original course code: CACS351; mapped course code: BCA352; curriculum key: 2018; semester: 6.
- Class load: 6 Hrs./Week (Theory: 3 Hrs, Practical: 3 Hrs); Credits: 3.
Note: The 2018 curriculum key cites older TU source material; confirm the edition before publication. This guide is a mapped archived outline and is not a new 2025 detailed syllabus.
Content audit (metadata)
- Unit count: 8
- Topic count: 47 (mapped archived outline topics)
- Covered topic count: 47
- Word count: ~9,800
- Status: staged (all TOC topics have substantive content)
- Unresolved items: Verify course code mapping, contact hours, and edition against an official TU source before publication; Mermaid diagrams omitted per "no decorative diagrams" — text explanations are provided instead.
- Label: mapped archived outline (2018 curriculum); not a new 2025 detailed syllabus.