0% found this document useful (0 votes)
3 views14 pages

API & Databases in AndroidStudio

This lecture covers the integration of APIs and databases in Android using XML and Kotlin. Students will learn about APIs, specifically REST APIs, and how to build a simple Student List App that fetches data from an API, displays it, and stores it in a local SQLite database. The lecture includes practical steps for setting up the app, including permissions, dependencies, data models, and UI design.

Uploaded by

Tehreem Fatima
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

API & Databases in AndroidStudio

This lecture covers the integration of APIs and databases in Android using XML and Kotlin. Students will learn about APIs, specifically REST APIs, and how to build a simple Student List App that fetches data from an API, displays it, and stores it in a local SQLite database. The lecture includes practical steps for setting up the app, including permissions, dependencies, data models, and UI design.

Uploaded by

Tehreem Fatima
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

📘 CHAPTER 6 LECTURE

Working with APIs & Databases (Android – XML + Kotlin)

🎯 Lecture Objectives (Tell Students)

By the end of this chapter, you will:

 Understand what APIs are


 Learn how Android apps fetch data from the internet
 Store data locally using SQLite
 Build a simple working app using API + Database

🟢 PART 1: UNDERSTANDING APIs


(Simple Explanation)
🔹 What is an API?

An API (Application Programming Interface) allows two applications to talk to each


other.

📱 Example:

 Your app → asks weather data


 Server → sends weather data

👉 Your app does not know how data is stored


👉 It only knows how to ask

🔹 Real-Life Analogy

📞 Calling a restaurant:

 You order food (request)


 Restaurant sends food (response)
🔹 Types of APIs (Explain Only Key Ideas)

✅ REST API (Most Common)

 Uses HTTP methods


 Returns JSON
 Easy & fast

Method Use

GET Fetch data

POST Send data

PUT Update data

DELETE Delete data

📌 We will use REST API


PART 2: SIMPLE APP WE WILL BUILD
📱 App Name: Student List App
Features:

 Fetch students from API


 Show them on screen
 Save data into SQLite
 Load from database if needed

PART 3: API INTEGRATION (ANDROID)


🔹 Step 1: Add Internet Permission

📄 [Link]

<uses-permission android:name="[Link]"/>

🔹 Step 2: Add Dependencies (Retrofit)

📄 [Link] (Module)

implementation '[Link].retrofit2:retrofit:2.9.0'
implementation '[Link].retrofit2:converter-gson:2.9.0'

🔹 Step 3: Data Model

📄 [Link]

data class Student(


val id: Int,
val name: String,
val email: String
)
🔹 Step 4: API Interface

📄 [Link]

import [Link]
import [Link]

interface ApiService {

@GET("users")
fun getStudents(): Call<List<Student>>
}

We’ll use:

[Link]

🔹 Step 5: Retrofit Instance

📄 [Link]

import [Link]
import [Link]

object RetrofitClient {

private const val BASE_URL = "[Link]

val api: ApiService by lazy {


[Link]()
.baseUrl(BASE_URL)
.addConverterFactory([Link]())
.build()
.create(ApiService::[Link])
}
}
PART 4: UI (XML – Traditional)
📄 activity_main.xml

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<Button
android:id="@+id/btnFetch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch Students from API"/>

<TextView
android:id="@+id/txtResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result will appear here"
android:paddingTop="16dp"/>
</LinearLayout>

PART 5: MAIN ACTIVITY (API CALL)


📄 [Link]

import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]

class MainActivity : AppCompatActivity() {

lateinit var txtResult: TextView


lateinit var btnFetch: Button
lateinit var dbHelper: DatabaseHelper

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
setContentView([Link].activity_main)

txtResult = findViewById([Link])
btnFetch = findViewById([Link])
dbHelper = DatabaseHelper(this)

[Link] {
fetchStudents()
}
}
private fun fetchStudents() {
[Link]().enqueue(object :
Callback<List<Student>> {
override fun onResponse(
call: Call<List<Student>>,
response: Response<List<Student>>
) {
if ([Link]) {
val students = [Link]()
[Link] = ""

students?.forEach {
[Link]("${[Link]}\n")
[Link]([Link], [Link])
}
}
}

override fun onFailure(call: Call<List<Student>>, t: Throwable)


{
[Link] = "Error fetching data"
}
})
}
}

PART 6: LOCAL DATABASE (SQLite)


📄 [Link]

import [Link]
import [Link]
import [Link]
import [Link]

class DatabaseHelper(context: Context) :


SQLiteOpenHelper(context, "StudentDB", null, 1) {

override fun onCreate(db: SQLiteDatabase) {


[Link](
"CREATE TABLE students (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"email TEXT)"
)
}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion:


Int) {
[Link]("DROP TABLE IF EXISTS students")
onCreate(db)
}

fun insertStudent(name: String, email: String) {


val db = writableDatabase
val values = ContentValues()
[Link]("name", name)
[Link]("email", email)
[Link]("students", null, values)
}
}

PART 7: HOW API + DATABASE WORK


TOGETHER
Flow (Explain on Board):
Button Click

API Call

Data Received (JSON)

Displayed on Screen

Saved into SQLite

🏫 STUDENT EXERCISES
📝 Exercise 1 (Easy)

 Change button text


 Display email with name

📝 Exercise 2 (Medium)

 Add another button: “Load from Database”

📝 Exercise 3 (Advanced)

 Prevent duplicate records in SQLite


📘 COMPLETE UNDERSTANDING OF
THE STUDENT LIST APP
(API + SQLite | XML + Kotlin)

🟢 1. [Link] (Permission)
<uses-permission android:name="[Link]"/>
Explanation:

 Android blocks internet access by default


 This line tells Android:

“My app is allowed to use the internet”

📌 Without this → API will never work

🟢 2. [Link] (Data Model)


data class Student(
val id: Int,
val name: String,
val email: String
)
Line-by-line:

 data class
→ Special Kotlin class to hold data only
 Student
→ Name of the model (represents one student)
 id, name, email
→ Variables coming from API

📌 API returns JSON like:

{
"id": 1,
"name": "Leanne Graham",
"email": "leanne@[Link]"
}

➡️ This class converts JSON into Kotlin object


🟢 3. [Link] (API Interface)
interface ApiService {

 Interface = blueprint
 Tells Retrofit what API to call

@GET("users")

 @GET → HTTP GET request


 "users" → endpoint

Full URL becomes:

[Link]

fun getStudents(): Call<List<Student>>

 getStudents() → function name


 Call<List<Student>>
o Call → network request
o List<Student> → response will be a list of students

📌 Retrofit automatically:

 Calls API
 Converts JSON to Student objects

🟢 4. [Link] (Network Setup)


object RetrofitClient {

 object → singleton (only one instance)


 Used so we don’t create Retrofit again and again

private const val BASE_URL = "[Link]

 Base address of API


 Endpoint will be added later

val api: ApiService by lazy {


 by lazy → created only when needed
 Saves memory

[Link]()

 Starts building Retrofit object

.baseUrl(BASE_URL)

 Sets API base URL

.addConverterFactory([Link]())

 Gson converts:
o JSON → Kotlin object
o Kotlin → JSON

.build()
.create(ApiService::[Link])

 Builds Retrofit
 Connects it to ApiService

📌 Now we can call:

[Link]()

🟢 5. activity_main.xml (UI Layout)


<LinearLayout

 LinearLayout → places items vertically

android:orientation="vertical"

 Items appear top to bottom


<Button
android:id="@+id/btnFetch"

 Button to start API call


 ID used in Kotlin

<TextView
android:id="@+id/txtResult"

 Displays student names


 Initially shows placeholder text

📌 XML = what user sees

🟢 6. [Link] (SQLite)
class DatabaseHelper(context: Context) :
SQLiteOpenHelper(context, "StudentDB", null, 1)
Explanation:

 SQLiteOpenHelper → Android’s database helper class


 "StudentDB" → database name
 1 → version number

override fun onCreate(db: SQLiteDatabase)

 Called only once


 When database is created first time

[Link](
"CREATE TABLE students (...)"
)

 SQL command
 Creates table with:
o id
o name
o email

📌 SQLite = offline storage


fun insertStudent(name: String, email: String)

 Function to save data

val values = ContentValues()

 Container to store key-value pairs

[Link]("name", name)
[Link]("email", email)

 Column name → value

[Link]("students", null, values)

 Inserts row into database

🟢 7. [Link] (Main Logic)


class MainActivity : AppCompatActivity()

 Activity = one screen


 Entry point of app

lateinit var btnFetch: Button


lateinit var txtResult: TextView
lateinit var dbHelper: DatabaseHelper

 Declares variables
 lateinit → initialized later

setContentView([Link].activity_main)

 Connects XML with Kotlin

btnFetch = findViewById([Link])
 Links XML button to Kotlin variable

[Link] {
fetchStudents()
}

 When button is clicked


 Call fetchStudents() function

🟢 8. fetchStudents() Function
[Link]().enqueue(...)

 Calls API
 enqueue → asynchronous (does not freeze app)

onResponse(...)

 Runs when API succeeds

if ([Link])

 Checks if server returned data correctly

[Link]()?.forEach {

 Loops through each student

[Link]("${[Link]}\n")

 Displays student name on screen

[Link]([Link], [Link])

 Saves data locally


📌 This is the key concept

API data → UI → Database

onFailure(...)

 Runs if:
o No internet
o Server error

🔁 COMPLETE APP FLOW (DIAGRAM)


User clicks button

API request sent

JSON received

Converted to objects

Displayed on screen

Saved in SQLite

You might also like