Share
Explore

Instructional Student Lab Lesson Activity Guide Notebook: Kotlin Android App Network Applications

Learning Outcomes:
Network Connectivity
Set the Instructions here on how to get an API Key from OpenWeather:
− Connect to REST API
Representational State Transfer

− Get data from API: Method call in your code
JSON : JavaScript Object Notation: Data Description Language
Weather App, Currency Converter, Google Earth

− Parse data from API + Converting to object

− Display parsed data in UI


Kotlin Android App Development: Network Connectivity and REST API Integration


Introduction



Welcome to this lecture on Kotlin Android app development, where we will explore the essential concepts and theory behind network connectivity, connecting to a REST API, getting data from an API, parsing data from an API, and displaying parsed data in a user interface.
By understanding these concepts, you will be able to build more complex and feature-rich Android applications in the future.


Network Connectivity



In modern mobile applications, it is essential to connect to the internet to access various resources and services.
Network connectivity in Android apps is achieved through the Android networking libraries, such as HttpURLConnection, OkHttp, and Retrofit.
These libraries facilitate communication between your app and remote servers using various protocols like HTTP and HTTPS.
SOAP: Simple Object Access Protocol

Permissions


To access the internet, your app needs to request the necessary permissions in the AndroidManifest.xml file. The INTERNET permission is required to access the internet, while the ACCESS_NETWORK_STATE permission allows you to check the network status.


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



Connecting to a REST API


A REST (Representational State Transfer) API is a set of rules that allows you to interact with web services using HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations (Create, Read, Update, Delete).
In Android apps, we can use Retrofit, a popular HTTP client library, to simplify the process of connecting to REST APIs.


Retrofit

Retrofit is a type-safe HTTP client library for Android and Java. It allows you to define API service interfaces, create instances of these interfaces, and make API calls easily. Retrofit uses annotations to describe HTTP requests, making your code more readable and maintainable.


Getting Data From an API


When you interact with a REST API, you send an HTTP request and receive a response, usually in JSON or XML format.
To get data from an API, you need to perform an HTTP GET request using Retrofit.
To do this, you need to define an API service interface with the appropriate annotations specifying the endpoint and HTTP method.


Parsing Data From an API


Once you receive the data from the API, you must parse it into a more usable format, like objects, to manipulate and display it in your app.

JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
In Kotlin Android app development, you can use libraries like Gson or Moshi to parse JSON data into custom data classes.

Displaying Parsed Data in a UI

After parsing the data, the next step is to display it in your app's user interface. One common way to display lists of data in Android apps is by using a RecyclerView.

RecyclerView


RecyclerView is a flexible and efficient Android UI component for displaying large sets of data in a scrolling list.
It efficiently recycles views to minimize memory usage and improve performance. To use a RecyclerView, you need to create an adapter that binds the data to the views and a layout manager that defines how the items are displayed.

Conclusion



In this lecture, we have covered the theory behind network connectivity, connecting to a REST API, getting data from an API, parsing data from an API, and displaying parsed data in a user interface.
Understanding these concepts will provide a strong foundation for building more complex and feature-rich Android applications in the future.

Lesson Overview

In this lab lesson activity,
you will learn how to develop an Android app using Kotlin with a focus on network connectivity. You will learn how to connect to a REST API, get data, parse it, convert it to objects, and display the parsed data in the user interface.

Prerequisites

Basic understanding of Kotlin
Android Studio installed on your computer
Familiarity with Android app development

Lesson Objectives


By the end of this lesson, you will be able to:
Connect to a REST API using Kotlin and Android Studio
Get data from the API
Parse the data and convert it into objects
Display the parsed data in the user interface

Lesson Outline

1. Network Connectivity

1.1. Setting up Android Studio project

Launch Android Studio and create a new project.
Choose an Empty Activity template.
Name your project, set the package name, and choose Kotlin as the programming language.
Click "Finish" to create the project.


1.2. Adding internet permission

In the AndroidManifest.xml file, add the following permission: done
<uses-permission android:name="android.permission.INTERNET" />


2. Connect to REST API


2.1. Adding dependencies



In the app-level build.gradle file, add the following dependencies:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}


Sync your project.

2.2. Creating Retrofit instance


Create a new Kotlin file and name it "ApiClient".
In the ApiClient.kt file, add the following code: Main Activity

import retrofit2.Response;
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import kotlin.reflect.KProperty

object ApiClient {
private const val BASE_URL = "https://api.example.com/"

private val lazyRetrofit = lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}

operator fun getValue(nothing: Nothing?, property: KProperty<*>): Retrofit {
return lazyRetrofit.value
}
}

Note: build.gradle (app)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}

android {
namespace 'com.example.april10a'
compileSdk 33

defaultConfig {
applicationId "com.example.april10a"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled 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 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.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'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

3. Get data from API: OpenWeather: get an API Key to work with

3.1. Defining API endpoints


Create a new Kotlin file and name it "ApiService".
In the ApiService.kt file, add the following code:
import retrofit2.http.GET

interface ApiService {
@GET("endpoint")
suspend fun getData(): Response<List<DataType>>
}

Replace "endpoint" with the desired API endpoint and "DataType" with the appropriate data type.
In a further step of this lab, we will get an API Key for OPEN Weather and hook up to that.
In the context of using Retrofit, "endpoint" refers to the specific API endpoint (or URL) you want to access, and "DataType" refers to the Java or Kotlin data class that represents the expected JSON response structure from that API.
For example, if you're working with a weather API with the base URL https://api.example.com/, and there's an endpoint /weather/{city} that returns weather information for a city, your endpoint would be /weather/{city}.
Next, you need to create a data class to represent the JSON response.
Let's say the JSON response looks like this:
{
"city": "New York",
"temperature": 75,
"humidity": 60
}


You would create a data class (in Java or Kotlin) like this:
data class WeatherData(
val city: String,
val temperature: Int,
val humidity: Int
)


Now, replace "endpoint" with /weather/{city} and "DataType" with WeatherData. Your Retrofit API interface would look something like this:

interface WeatherApi {
@GET("/weather/{city}")
suspend fun getWeatherData(@Path("city") city: String): Response<WeatherData>
}


So, in this example, you replace "endpoint" with /weather/{city} and "DataType" with WeatherData. You'll need to adjust these according to the specific API you're working with and the expected response structure.

3.2. Calling API endpoint

resume here:
In your main activity, create a function to call the API endpoint
private suspend fun getDataFromApi() {
val apiService = ApiClient.instance.create(ApiService::class.java)
val response = apiService.getData()

if (response.isSuccessful) {
val data = response.body()
} else {
// Handle error
}
}

4. Parse data from API + Converting to object

4.1. Creating data class


Create a new Kotlin file and name it "DataType".
In the DataType.kt file, add the following code:

data class DataType(
val property1: String,
val property2: String
// Add other properties as required
)

Replace "property1" and "property2" with the appropriate property names and types based on the API response.

4.2. Parsing JSON response


Modify the ApiService.kt file to include the GsonConverterFactory:

import retrofit2.converter.gson.GsonConverterFactory

val instance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}


5. Display parsed data in UI


5.1. Creating a RecyclerView


Add a RecyclerView to your activity's XML layout file:

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />


Create a new Kotlin file and name it "DataAdapter".
In the DataAdapter.kt file, create a class that extends RecyclerView.Adapter:

class DataAdapter(private val dataList: List<DataType>) : RecyclerView.Adapter<DataAdapter.DataViewHolder>() {

// Implement required methods

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.