Share
Explore

s24 MADS 4001 Intro to Android Development

info

Day 01: Introduction to Android

Introduction to Android architecture and app lifecycle
Fundamentals of the development environment and tools
Course Software Setup (Android Studio)
UI Components:
Working with Views (TextView, EditText, Button)
Handling event listeners for various UI Components

Day 02 : JULY 9

Intro to Android App Architecture
Activities and the activity lifecycle
What is an activity?
What is an activity lifecycle? (https://static.javatpoint.com/images/androidimages/Android-Activity-Lifecycle.png)

Coding Demo: Overriding the lifecycle functions and showing when they execute:
onCreate()
onStart()
onResume()
onPause()
onRestart()

UI Components, continued

Displaying an image using an ImageView and a file in the drawables folder

Programmatically updating the picture shown in an ImageView


Developing an Android APP means
Writing (1) Kotlin Code, (2) layout xml, (3) Gradle Build Scripts
in Android Studio Studio, and running this app in AVD or Physical Device
Within the context that you are sitting on top of the Android Runtime Environment → which gives you access to the device hardware via APIs ultimated provisioned by JNDI Driver Files.
(Want more details? Read my book!)

megaphone

Learning outcomes:

The elements of Android KOTLIN Applications and their architecture.

The elements of Android Kotlin applications are typically structured within a recommended architecture that ensures the development of robust, scalable, and maintainable apps.
The main elements and architecture of Android Kotlin applications include the key elements and architecture of Android Kotlin applications:
The 6 Key Elements of Android Application Architecture:

1. Activities and Fragments - The core UI components that represent screens and portions of the UI.
2. Layouts and Views - Define the structure and individual UI elements.
3. Intents - Messaging objects used to request actions from other app components.
4. Services - Background components for long-running operations.
5. Broadcast Receivers - Components that respond to system-wide broadcast messages.
6. Content Providers - Manage and share app data.

Architecture:
Android Kotlin apps typically follow an MVVM (Model-View-ViewModel) or Clean Architecture pattern.
This is similar to Model View Controller for Web Applications:
View : HTML, Android Screen: Point of Interaction with the User.
Controller: the set of classes which run the application: Deliver the Business Rules and Algorithms
Model: Data Store or data persistence layer. This is NOT the database itself. The Model is the wrapper or mediator that brokers connections to the database.
In the Android OS, there is a build in SQLite database. Accessible via the “Shared Preferences” Android Framework.
We also have the ROOMS Library.

With the following layers:
1. UI Layer - Activities/Fragments are used to build ViewModels

2. Domain Layer: The “controller” - the system partition in which code business rules and algorithms: == Simplest Example here is the MainActivity.kt file : the file in which we code what happens - Use Cases are boxes, descriptions of business processes, and how they Interact

3. Data Layer: The Persistence Layer - Repositories - Data Sources (local and remote)
This could be “on device” memory or remote API accessed memory.
Room Framework : built in SQLite db, good for storing preferences

MVVM Pattern: This architecture promotes:
Comparing MVC to MVVM: The big difference is:
In MVC: We do NOT allow Business Logic in the View Layer.
In MVVM, we put business logic in the view layer to simplify the design of the program.
- Separation of concerns - Testability - Maintainability - Scalability
The ViewModel acts as a bridge between the UI and business logic.
The “Persistence Layer” (the connection to your database) manage data operations across multiple sources.
This layered approach allows for a clean separation between the UI, business logic, and data management.
This architecture enables building robust, maintainable Android applications in Kotlin by organizing code into logical layers with clear responsibilities.
Citations: [1] https://developer.android.com/guide/components/fundamentals [2] https://www.scaler.com/topics/basic-android-elements-in-kotlin/ [3] https://reintech.io/blog/implementing-mvvm-architecture-kotlin [4] https://www.youtube.com/watch?v=4agk_yVY5z8 [5] https://github.com/emedinaa/kotlin-mvvm [6] https://github.com/android10/Android-CleanArchitecture-Kotlin [7] https://developer.android.com/topic/architecture [8] https://developer.android.com/topic/libraries/architecture/viewmodel [9] https://www.geeksforgeeks.org/components-android-application/ [10] https://kotlinlang.org/docs/android-overview.html [11] https://www.toptal.com/android/android-apps-mvvm-with-clean-architecture [12] https://dev.to/whatminjacodes/simple-example-of-mvvm-architecture-in-kotlin-4j5b [13] https://www.geeksforgeeks.org/android-architecture/ [14] https://www.geeksforgeeks.org/mvvm-model-view-viewmodel-architecture-pattern-in-android/

info

Lab Part 1: "Intro to Android App Architecture".

Here is a comprehensive lesson plan focusing on Activities and the activity lifecycle.
We'll use viewBindings and avoid findViewById as prescribed by current best practice.
Here's a detailed outline for the lesson:
This lesson plan covers the key aspects of Android app architecture, focusing on Activities and their lifecycle.
The coding demo and hands-on exercise will give students practical experience with implementing and observing the Activity lifecycle in action, using viewBinding in keeping with current Android Kotlin Application Development best practices.

Day 2 Class: Intro to Android App Architecture
1. Introduction (10 minutes) - Brief recap of previous class - Overview of today's topics:
Activities and Activity Lifecycle
2. What is an Activity? (15 minutes) - Definition: A single, focused thing that the user can do. - Relation to app screens - Role in the Android app architecture
3. Activity Lifecycle (20 minutes) - Explanation of the Activity Lifecycle concept - Visual representation: [Activity Lifecycle Diagram](https://static.javatpoint.com/images/androidimages/Android-Activity-Lifecycle.png) - Detailed explanation of each lifecycle state
image.png
4. Lifecycle Methods (30 minutes) - Overview of main lifecycle methods: - onCreate() - onStart() - onResume() - onPause() - onStop() - onRestart() - onDestroy() - When and why each method is called
5. Coding Demo:
Overriding Lifecycle Methods (45 minutes) - Setup a new Android project in Android Studio - Implement viewBinding - Override lifecycle methods and add logging statements - Run the app and demonstrate when each method is called (debugger and logcat)
Here's a basic code structure for the lifecycle demo:
```kotlin class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) Log.d(TAG, "onCreate called")
binding.buttonNext.setOnClickListener { startActivity(Intent(this, SecondActivity::class.java)) } }
override fun onStart() { super.onStart() Log.d(TAG, "onStart called") }
override fun onResume() { super.onResume() Log.d(TAG, "onResume called") }
override fun onPause() { super.onPause() Log.d(TAG, "onPause called") }
override fun onStop() { super.onStop() Log.d(TAG, "onStop called") }
override fun onRestart() { super.onRestart() Log.d(TAG, "onRestart called") }
override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy called") } } ```
6. Hands-on Exercise (30 minutes) - Students create a simple two-activity app - Implement viewBinding in both activities - Override lifecycle methods in both activities - Add logging statements to track lifecycle method calls - Test the app and observe the lifecycle method execution order



minus

Code Lab 1

Android Kotlin project that demonstrates the activity lifecycle events.
This project will work with the latest Android Studio version we are using in class.
First, create a new Android project in Android Studio:
Choose "Empty Views Activity" as the template
Name your project "LifecycleDemoApp"
Choose Kotlin as the language
Set Minimum SDK to API 24: Android 7.0 (Nougat)
Application that we will build: Here are the necessary files with their content:
(Defines 1 Activity) => MainActivity.kt: (Business Logic, or “controller” of the application).
package com.example.lifecycledemoapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.lifecycledemoapp.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
logAndUpdateStatus("onCreate")
}

override fun onStart() {
super.onStart()
logAndUpdateStatus("onStart")
}

override fun onResume() {
super.onResume()
logAndUpdateStatus("onResume")
}

override fun onPause() {
super.onPause()
logAndUpdateStatus("onPause")
}

override fun onStop() {
super.onStop()
logAndUpdateStatus("onStop")
}

override fun onRestart() {
super.onRestart()
logAndUpdateStatus("onRestart")
}

override fun onDestroy() {
super.onDestroy()
logAndUpdateStatus("onDestroy")
}

private fun logAndUpdateStatus(status: String) {
Log.d(TAG, status)
binding.statusTextView.text = "${binding.statusTextView.text}\n$status"
}
}

activity_main.xml: (Controls the layout of widgets on the Screen - buttons, fields): 1 : 1 layout file to business logic file)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/statusTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lifecycle Events:"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Note: Ensure that viewBinding is enabled:
1. make sure your module-level build.gradle.kts file includes the following in the android block:
kotlin
Copy
buildFeatures {
viewBinding = true
}
This application code uses viewBinding, careful to avoid the no-longer acceptable findViewById, adhering to the requirements to work with latest Android Kotlin Best Practices. The functionality demonstrates lifecycle events by logging them and updating the UI.
Your App will have 2 Build GRADLE Files : 1 for entire application, and 1 (or more) for each package.

build.gradle.kts (Project level): 1 for the entire application

plugins {
id("com.android.application") version "8.2.2" apply false
id("org.jetbrains.kotlin.android") version "1.9.22" apply false
}

build.gradle.kts (Module level): → A module is a Package (directory)

plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}

android {
namespace = "com.example.lifecycledemoapp"
compileSdk = 34

defaultConfig {
applicationId = "com.example.lifecycledemoapp"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}

dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}

megaphone

The error "Unresolved reference: databinding" in your Android Studio project using Kotlin typically arises when Data Binding isn't correctly configured or recognized. Here's how to fix it:

1. Enable Data Binding in Build Configuration:
Open your module-level build.gradle.kts file (usually build.gradle.kts (Module: app) in the image).
Within the android {} block, add the following:
KotlinbuildFeatures { dataBinding = true } Use code with caution.content_copy
If not present, add the android block before adding the buildFeatures block.
2. Verify Layout File Structure:
Ensure your layout files (e.g., activity_main.xml) are wrapped in a <layout> tag:
XML<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> </data> </layout> Use code with caution.content_copy
3. Rebuild and Sync Project:
Click "Sync Project with Gradle Files" (the elephant icon in the toolbar).
If that doesn't resolve the issue, try "Clean Project" followed by "Rebuild Project."
4. Check for Typos and Naming Conventions:
Double-check the spelling of ActivityMainBinding. It must match the name of your layout file exactly (e.g., activity_main.xml -> ActivityMainBinding).
Ensure you're using the correct package name when referencing the generated binding class.
5. Invalidate Caches and Restart:
Go to "File" -> "Invalidate Caches / Restart..."
Click "Invalidate and Restart" to clear any cached data that might be causing the error.
Additional Tips:
Update Gradle Version: Make sure you're using the latest stable version of Gradle and the Android Gradle Plugin. Update them in the project-level build.gradle.kts file.
Check Dependencies: Verify that the Data Binding dependency is correctly added in your module-level build.gradle.kts file. Look for:
implementation("androidx.databinding:databinding-runtime:x.x.x") //Replace x.x.x with the version number.
Kotlin Plugin: Confirm that the Kotlin Gradle plugin is applied in your project-level build.gradle.kts file.
Import Correctly: Ensure you have imported the necessary classes. For example, you should see the following import statement in your code:
import com.example.lifecycledemoapp.databinding.ActivityMainBinding
Image-Specific Note:
The error "Unresolved reference: ActivityMainBinding" in the image indicates that the binding class itself hasn't been generated or recognized. Make sure you've followed the steps to enable Data Binding and rebuild your project.
Let me know if you still face any issues after trying these solutions!
AndroidManifest.xml: The “definer” configuration for the entire app.
Upload to Google Play store? The information to package the app for sale would be contained here.
xml
Copy
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.LifecycleDemoApp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.