0% found this document useful (0 votes)
818 views

IT3681 Mobile Applications Development Laboratory

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
818 views

IT3681 Mobile Applications Development Laboratory

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

lOMoARcPSD|37512785

IT3681 Mobile Applications Development Laboratory

Information Technology (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by RISHIKESH KA CSE ([email protected])
lOMoARcPSD|37512785

IT3681 MOBILE APPLICATIONS DEVELOPMENT LABORATORY

LIST OF EXPERIMENTS

1. Study and installation of Flutter/Kotlin multi-platform environment


2. Develop an application that uses Widgets, GUI components, Fonts, and Colors.
3. Develop a native calculator application.
4. Develop a gaming application that uses 2-D animations and gestures.
5. Develop a movie rating application (similar to IMDB)
6. Develop an application to connect to a web service and to retrieve data with HTTP.
7. Develop a simple shopping application.
8. Design a web server supporting push notifications.
9. Develop an application by integrating Google maps

10.Mini Projects involving Flutter/Kotlin multi-platform

TOTAL: 45 PERIODS

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No : 1
Study and installation of Flutter/Kotlin multi-platform
Date: environment

Aim:

To Study and installation of Flutter/Kotlin multi-platform environment

Procedure:

Flutter:

Install Flutter SDK:

Download the Flutter SDK from the official Flutter website.


Extract the downloaded archive and add the flutter/bin directory to your system PATH.

Set up an IDE (Integrated Development Environment):

You can use Android Studio, IntelliJ IDEA, or Visual Studio Code for Flutter development.
Install the Flutter and Dart plugins for your chosen IDE.

Run flutter doctor:

Open a terminal and run flutter doctor to check for any dependencies that need to be
installed. Follow the instructions provided by flutter doctor to resolve any issues.

Create a Flutter Project:

Run the following commands in your terminal:

flutter create my_flutter_project


cd my_flutter_project

Run the App:


Connect a device or start an emulator and run flutter run in the project directory.

Kotlin:

Install Kotlin:
You can install Kotlin by following the instructions on the official Kotlin website.
Set up an IDE:
Kotlin Multiplatform projects are well-supported in IntelliJ IDEA. Install the Kotlin plugin
for your IDE.

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Create a Kotlin Multiplatform Project:


Create a new Kotlin Multiplatform project using a template or set it up manually.
Configure Shared Code:
Define the common code that will be shared across platforms. This code will be written
in Kotlin and can include business logic, data models, etc.
Platform-Specific Code:
Implement platform-specific code for Android and iOS. This involves creating separate
modules or directories for each platform and writing the necessary code in Kotlin (for
common logic) and Swift/Kotlin (for platform-specific code).
Build and Run:
Build the project using the appropriate build command for your project structure (e.g.,
Gradle for Android). Run the app on Android and iOS devices/emulators
Remember that integrating Flutter and Kotlin Multiplatform in the same project can be
complex, and it may require additional setup and configuration. Ensure that you
carefully follow the documentation for both technologies and understand the
integration points.

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. What are the key advantages of using a Flutter/Kotlin multi-platform environment


for mobile app development?
2. Define the term "Kotlin Multiplatform.
3. Explain how Flutter facilitates a reactive UI development approach.
4. What is the role of the "pubspec.yaml" file in a Flutter project?
5. How does Flutter's hot reload feature enhance the development workflow?

Postlab Questions:

1. What were the main challenges you encountered during the installation process, and
how did you overcome them?
2. Reflect on the integration of Flutter and Kotlin Multiplatform. In what ways did this
combination enhance or complicate the development workflow?
3. Discuss any insights gained from the process of sharing code between Flutter and Kotlin
Multiplatform. Were there any unexpected benefits or challenges?
4. Consider the testing phase. How did the multi-platform nature of the project impact
testing strategies, and what adjustments were made to ensure thorough testing across
platforms?
5. Evaluate the overall development experience with Flutter and Kotlin Multiplatform.
What aspects would you highlight as strengths, and are there areas that could be
improved in future projects?

Results:

Thus the Study and installation of Flutter/Kotlin multi-platform environment has been
executed successfully.

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No:2

Develop an application that uses Widgets, GUI components, Fonts, and Colors.
Date:

Aim:

Develop an application that uses Widgets, GUI components, Fonts, and Colors.

Procedure:

1) Open your preferred Kotlin IDE.


2) Create a new Kotlin project.
3) Download the JavaFX SDK from the official website.
4) Extract the downloaded archive to a location on your computer.
5) In your Kotlin project, add the JavaFX library to your project's dependencies.
6) Create a new Kotlin file for your main application class, e.g., MyApp.kt.
7) Copy and paste the Kotlin code provided in the previous response into this file.
8) Open the Run/Debug Configuration in your IDE.
9) Add the following VM options:
--module-path /path/to/javafx-sdk-17/lib --add-modules javafx.controls,javafx.fxml
Replace /path/to/javafx-sdk-17 with the actual path to your JavaFX SDK.
Run the main function in your MyApp.kt file.

Program:

import javafx.application.Application

import javafx.geometry.Insets

import javafx.scene.Scene

import javafx.scene.control.Button

import javafx.scene.control.ComboBox

import javafx.scene.control.Label

import javafx.scene.control.TextField

import javafx.scene.layout.VBox

import javafx.scene.text.Font

import javafx.stage.Stage

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

10

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

class MyApp : Application() {

override fun start(primaryStage: Stage) {

primaryStage.title = "Widget App"

val root = VBox(10.0)

root.padding = Insets(10.0)

// Set a custom font

val customFont = Font("Arial", 12.0)

// Set background color

root.style = "-fx-background-color: #f0f0f0;"

// Create a label

val label = Label("Welcome to Widget App")

label.font = customFont

root.children.add(label)

// Create a button

val button = Button("Click Me!")

button.font = customFont

button.setOnAction { onButtonClick() }

root.children.add(button)

// Create a text field

val textField = TextField()

textField.font = customFont

root.children.add(textField)

// Create a combo box

val comboBoxValues = listOf("Option 1", "Option 2", "Option 3")

val comboBox = ComboBox<String>()

comboBox.items.addAll(comboBoxValues)

11

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

12

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

comboBox.font = customFont

root.children.add(comboBox)

val scene = Scene(root, 300.0, 200.0)

primaryStage.scene = scene

primaryStage.show()

private fun onButtonClick() {

println("Button Clicked!")

fun main() {

Application.launch(MyApp::class.java)

13

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

14

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. What is a widget in the context of GUI development?


2. Why is color important in GUI design? Give a brief explanation.
3. How can the choice of font impact the user experience in a GUI application?
4. Briefly explain why event handling is crucial in GUI programming.
5. Name one layout manager and describe its role in organizing GUI components.

Postlab Questions:

1. Provide a code snippet showcasing the implementation of a button widget in your GUI
application.
2. Mention one widget in your application and describe how you applied color and font
customization to it.
3. Give an example of a user interaction event in your GUI application and how it triggers a
response.
4. Briefly mention one challenge you faced during development and how you addressed it.
5. Suggest one potential improvement for your GUI application in terms of features or user
interface enhancements.

Results:

Thus the application that uses Widgets, GUI components, Fonts, and Colors has been executed
successfully.

15

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

16

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 3
Develop a native calculator application.
Date:

Aim:

To develop a native calculator application.

Procedure:

Create a new Android Studio Project:

Open Android Studio and create a new project.

Choose "Empty Activity" template.

Design the UI:

Open res/layout/activity_main.xml and replace its content with the following Xml code

Define Button IDs and Operators:

Open MainActivity.kt and replace its content with the following kotlin code

Run your app:

Connect your Android device or start an emulator.

Click on the "Run" button in Android Studio.

Program:

Xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<EditText

android:id="@+id/inputText"

17

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

18

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="16dp"

android:layout_marginBottom="16dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:hint="Enter expression"

android:inputType="none"

android:textAlignment="center" />

<GridLayout

android:id="@+id/gridLayout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/inputText"

android:layout_marginTop="16dp"

android:columnCount="4"

android:orientation="horizontal">

<!-- Buttons for digits and operators go here -->

</GridLayout>

</RelativeLayout>

Kotlin:

import android.os.Bundle

import android.view.View

import android.widget.Button

import android.widget.EditText

import androidx.appcompat.app.AppCompatActivity

19

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

20

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

import net.objecthunter.exp4j.ExpressionBuilder

class MainActivity : AppCompatActivity() {

private lateinit var inputText: EditText

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

inputText = findViewById(R.id.inputText)

val buttons = intArrayOf(

R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3,

R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7,

R.id.btn8, R.id.btn9, R.id.btnAdd, R.id.btnSub,

R.id.btnMul, R.id.btnDiv, R.id.btnDot, R.id.btnEquals

for (buttonId in buttons) {

val button = findViewById<Button>(buttonId)

button.setOnClickListener { onButtonClick(it) }

private fun onButtonClick(view: View) {

val currentText = inputText.text.toString()

val buttonText = (view as Button).text.toString()

when (view.id) {

R.id.btnEquals -> evaluateExpression(currentText)

R.id.btnDot -> handleDotButtonClick(currentText)

else -> inputText.setText("$currentText$buttonText")

21

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

22

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

private fun evaluateExpression(expression: String) {

try {

val result = ExpressionBuilder(expression).build().evaluate()

inputText.setText(result.toString())

} catch (e: Exception) {

inputText.setText("Error")

} private fun handleDotButtonClick(currentText: String) {

val lastOperatorIndex = getLastOperatorIndex(currentText)

val lastDotIndex = currentText.lastIndexOf(".")

if (lastDotIndex > lastOperatorIndex) {

// If there is already a dot after the last operator, do nothing.

return

} inputText.setText("$currentText.")

} private fun getLastOperatorIndex(text: String): Int {

val operators = charArrayOf('+', '-', '*', '/')

var lastOperatorIndex = -1

for (operator in operators) {

val index = text.lastIndexOf(operator)

if (index > lastOperatorIndex) {

lastOperatorIndex = index

} return lastOperatorIndex

23

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

24

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. What are the key UI components needed for a calculator app?


2. How will you manage user input for numeric and operator buttons?
3. Briefly explain your approach to evaluating mathematical expressions.
4. How will you handle and communicate errors during calculation?
5. What are the main test cases for ensuring your calculator app's correctness?

Postlab Questions:

1. How did your design choices contribute to the user experience?


2. Discuss any challenges encountered during app implementation.
3. What additional features would you add to improve the app?
4. Reflect on the effectiveness of your testing plan.
5. How would you incorporate user feedback into future versions?

Results:

Thus the program to develop a native calculator application has been executed successfully.

25

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

26

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 4
Develop a gaming application that uses 2-D animations and gestures.
Date:

Aim:

To develop a gaming application that uses 2-D animations and gestures.

Procedure:

1) Install Android Studio.


2) Set up a new project using Kotlin and integrate LibGDX.
3) Create 2D sprites for characters, backgrounds, and other elements using graphic design
tools.
4) Animate characters using LibGDX's animation support.
5) Utilize LibGDX's gesture detection or implement a custom gesture recognition system.
6) Implement controls that respond to gestures for player navigation and interaction.
7) Define core game mechanics, challenges, and rewards, integrating gestures into
gameplay.
8) Create different levels with increasing difficulty and design environments that
encourage gesture-based interactions.
9) Add background music, sound effects, and any necessary audio assets.
10) Regularly test the game on Android devices to identify and fix bugs. Ensure smooth
gesture-based interactions.
11) Optimize the game for performance, considering the limitations of mobile devices.
12) Prepare the game for release by configuring Android-specific settings.
13) Publish the game on the Google Play Store.

Program:

Main Game Class:

import com.badlogic.gdx.ApplicationAdapter

import com.badlogic.gdx.Gdx

import com.badlogic.gdx.graphics.GL20

import com.badlogic.gdx.graphics.Texture

import com.badlogic.gdx.graphics.g2d.SpriteBatch

class GestureQuest : ApplicationAdapter() {

private lateinit var batch: SpriteBatch

private lateinit var img: Texture

27

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

28

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

override fun create() {

batch = SpriteBatch()

img = Texture("badlogic.jpg") // Replace with your own image file

}override fun render() {

Gdx.gl.glClearColor(1f, 1f, 1f, 1f)

Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

batch.begin()

batch.draw(img, 0f, 0f)

batch.end()

} override fun dispose() {

batch.dispose()

img.dispose()

Gesture Recognition:

import com.badlogic.gdx.Gdx

import com.badlogic.gdx.InputProcessor

class MyInputProcessor : InputProcessor {

override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {

// Handle touch down event

return true

override fun keyDown(keycode: Int): Boolean {

// Handle key down event

return false

29

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

30

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

// Implement other InputProcessor methods as needed

override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int) {}

override fun keyUp(keycode: Int) {}

override fun keyTyped(character: Char) = false

override fun touchDragged(screenX: Int, screenY: Int, pointer: Int) {}

override fun mouseMoved(screenX: Int, screenY: Int) {}

override fun scrolled(amount: Int) {}

To use this input processor in your main game class, add the following code in the
create method:

val inputProcessor = MyInputProcessor()

Gdx.input.inputProcessor = inputProcessor

31

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

32

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. What is your game about?


2. How will players interact with the game using gestures?
3. Why are you using 2D animations in your game?
4. Why did you choose Kotlin for development?
5. How are you ensuring that gestures are easy for players to understand?

Postlab Questions:

1. What were the main challenges during development?


2. How did users respond to the gesture controls?
3. What did players say about the game during testing?
4. What aspects of the game would you improve?
5. What updates or expansions do you envision for your game?

Results:

Thus the program to develop a gaming application that uses 2-D animations and gestures has
been executed successfully.

33

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

34

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 5
Develop a movie rating application (similar to IMDB)
Date:

Aim:

To develop a movie rating application (similar to IMDB).

Procedure:

1) Install Java and Kotlin.


2) Set up your preferred IDE (IntelliJ IDEA is popular for Kotlin development).
3) Use the Spring Initializer to generate a new Spring Boot project with Kotlin and your
preferred dependencies (Spring Web, Spring Data JPA, etc.).
4) Define entities for movies, users, reviews, etc.
5) Use Spring Data JPA to interact with the database.
6) Create controllers for handling HTTP requests (e.g., movie listing, user authentication,
review submission).
7) Implement services to handle business logic.
8) Set up Spring Security for user authentication.
9) Integrate Spring Security for user registration, login, and profile management.
10) Allow users to submit and retrieve movie ratings.
11) Calculate and display average ratings.
12) Implement endpoints for users to submit and retrieve reviews.
13) Add a comment system for reviews.
14) Use a front-end framework (e.g., React, Angular, Vue) or templating engine (Thymeleaf)
to create the user interface.
15) Implement pages for browsing movies, viewing details, and submitting reviews.
16) Implement search functionality using query parameters or a dedicated search endpoint.
17) Write unit tests and integration tests for your Kotlin code.
18) Use testing libraries like JUnit and Mockito.
19) Deploy your Spring Boot application to a platform like Heroku, AWS, or any other of
your choice.
20) Implement security best practices, such as input validation and securing API endpoints.
21) Gather user feedback and consider adding new features or improving existing ones.
22) Implement monitoring tools to track application performance.
23) Regularly update dependencies and address security vulnerabilities.

Program:

data class Movie(val title: String, val genre: String, val releaseYear: Int)

data class Rating(val user: String, val movie: String, val rating: Double)

class MovieRatingSystem {

private val movies = mutableListOf<Movie>()

35

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

36

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

private val ratings = mutableListOf<Rating>()

fun addMovie(movie: Movie) {

movies.add(movie)

fun rateMovie(user: String, movieTitle: String, rating: Double) {

val movie = movies.find { it.title == movieTitle }

if (movie != null) {

val userRating = Rating(user, movieTitle, rating)

ratings.add(userRating)

println("Rating added successfully.")

} else {

println("Movie not found.")

fun getAverageRating(movieTitle: String): Double {

val movieRatings = ratings.filter { it.movie == movieTitle }

return if (movieRatings.isNotEmpty()) {

val totalRating = movieRatings.map { it.rating }.sum()

totalRating / movieRatings.size

} else {

0.0

fun listMovies() {

movies.forEach {

println("${it.title} (${it.releaseYear}) - ${it.genre}")

37

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

38

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

fun main() {

val movieRatingSystem = MovieRatingSystem()

// Adding movies

movieRatingSystem.addMovie(Movie("Inception", "Sci-Fi", 2010))

movieRatingSystem.addMovie(Movie("The Shawshank Redemption", "Drama", 1994))

movieRatingSystem.addMovie(Movie("The Dark Knight", "Action", 2008))

// Listing movies

println("Available Movies:")

movieRatingSystem.listMovies()

// Rating movies

movieRatingSystem.rateMovie("user1", "Inception", 9.0)

movieRatingSystem.rateMovie("user2", "Inception", 8.5)

movieRatingSystem.rateMovie("user1", "The Shawshank Redemption", 9.5)

// Getting average ratings

println("Average Rating for Inception: ${movieRatingSystem.getAverageRating("Inception")}")

println("Average Rating for The Shawshank Redemption:


${movieRatingSystem.getAverageRating("The Shawshank Redemption")}")

println("Average Rating for The Dark Knight: ${movieRatingSystem.getAverageRating("The


Dark Knight")}")

39

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

40

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. Which entities are crucial for storing movie information in the database?
2. How will user authentication be handled for secure access?
3. What method will be used to calculate average movie ratings?
4. Which front-end technology will be used for the user interface?
5. What approach will be taken to implement search functionality?

Postlab Questions:

1. How is user feedback collected and utilized for improvements?


2. Are there any identified performance bottlenecks with an increasing user base?
3. What security measures were implemented to protect user data?
4. Based on feedback, what features are considered for future releases?
5. Reflect on challenges faced during development and key takeaways for future projects?

Results:

Thus the program to develop a movie rating application (similar to IMDB) has been executed
successfully.

41

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

42

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 6

Develop an application to connect to a web service and to retrieve data with HTTP.
Date:

Aim:

To develop an application to connect to a web service and to retrieve data with HTTP.

Procedure:

1) Use your preferred IDE (such as IntelliJ IDEA) or a build tool (such as Gradle) to create a
new Kotlin project.
2) If you're using Gradle, add the following dependencies to your build.gradle.kts (for
Kotlin DSL) or build.gradle (for Groovy DSL):
implementation "io.ktor:ktor-client-apache:$ktor_version"
implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-client-serialization:$ktor_version"
3) Make sure to replace $ktor_version with the version of Ktor you want to use.
4) In your project, create a Kotlin file (e.g., Main.kt) to write your application code.
5) Write the code in 'Main.kt'
6) Use your IDE or build tool to run the Kotlin application. The program will make a GET
request to the specified API URL, retrieve data, and print it to the console.

Program:

Main.kt

import io.ktor.client.HttpClient

import io.ktor.client.engine.apache.Apache

import io.ktor.client.request.get

suspend fun fetchData(url: String): String {

val client = HttpClient(Apache)

return try {

val response = client.get<String>(url)

response

} finally {

client.close()

43

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

44

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

fun main() {

val apiUrl = "https://api.example.com/data"

try {

val result = fetchData(apiUrl)

println("Data received: $result")

} catch (e: Exception) {

println("Error: ${e.message}")

45

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

46

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. Have you installed the Kotlin plugin and configured your IDE for Kotlin development?
2. Do you know the API endpoint and data format of the web service?
3. Are you familiar with Ktor for making HTTP requests in Kotlin?
4. Have you considered potential exceptions during HTTP requests, and how will you
handle them?
5. If required, how are you handling authentication for the web service?

Postlab Questions:

1. Have you tested your application with different API scenarios?


2. Did you optimize your code for performance, especially for multiple requests?
3. How does your application handle user experience during HTTP request wait times?
4. Have you considered scalability for a large number of concurrent requests?
5. Is there clear documentation for setting up, configuring, and using your application?

Results:

Thus the program to develop an application to connect to a web service and to retrieve data
with HTTP has been executed successfully.

47

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

48

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 7
Develop a simple shopping application.
Date:

Aim:

To Develop a simple shopping application.

Procedure:

1) Define the Product Data Class


2) Define Procedures for Displaying Products, Adding to Cart, and Viewing Cart
3) Implement the Main Shopping Cart Logic
4) Compile and run the Kotlin program
5) interact with the simple shopping app by choosing options from the menu.

Program:

import java.util.Scanner

data class Product(val id: Int, val name: String, val price: Double)

fun displayProducts(products: List<Product>) {

println("\nAvailable Products:")

for (product in products) {

println("${product.id}. ${product.name} - $${product.price}")

fun addToCart(cart: MutableList<Product>, product: Product) {

cart.add(product)

println("${product.name} added to the cart.")

fun viewCart(cart: List<Product>) {

if (cart.isEmpty()) {

println("Your cart is empty.")

} else {

49

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

50

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

println("Your Cart:")

for ((index, item) in cart.withIndex()) {

println("${index + 1}. ${item.name} - $${item.price}")

val totalPrice = cart.sumByDouble { it.price }

println("Total: $$totalPrice")

fun main() {

val scanner = Scanner(System.`in`)

val cart = mutableListOf<Product>()

val products = listOf(

Product(1, "Product A", 10.99),

Product(2, "Product B", 19.99),

Product(3, "Product C", 7.49)

println("Welcome to the Simple Shopping App!")

while (true) {

println("\nMenu:")

println("1. View Products")

println("2. Add to Cart")

println("3. View Cart")

println("4. Exit")

print("Enter your choice: ")

when (scanner.nextInt()) {

1 -> {

51

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

52

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

displayProducts(products)

2 -> {

println("\nEnter the product ID to add to cart:")

val productId = scanner.nextInt()

val selectedProduct = products.find { it.id == productId }

if (selectedProduct != null) {

addToCart(cart, selectedProduct)

} else {

println("Invalid product ID. Please try again.")

3 -> {

viewCart(cart)

4 -> {

println("Thank you for using the Simple Shopping App. Exiting...")

return

else -> {

println("Invalid choice. Please enter a valid option.")

53

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

54

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. What is a data class in Kotlin?


2. Define MutableList in Kotlin.
3. How is the when statement used in Kotlin?
4. What is the role of the Scanner class in Kotlin?
5. Where does the execution of a Kotlin program begin?

Postlab Questions:

1. How does a data class simplify code for representing objects?


2. What advantage does a MutableList provide in a shopping cart?
3. How does the when statement improve code readability?
4. Why is the Scanner class essential for user interaction?
5. Explain the role of the main function in a Kotlin program.

Results:

Thus the program to develop a simple shopping application has been executed successfully.

55

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

56

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 8
Design a web server supporting push notifications.
Date:

Aim:

To design a web server supporting push notifications.

Procedure:

1) Create a new Kotlin project: Use your preferred IDE or build tool to create a new Kotlin
project.
2) Add Ktor Dependencies: Open your build.gradle.kts (or build.gradle) file and include the
following dependencies for Ktor:

plugins {

kotlin("jvm") version "1.5.31"

id("io.ktor") version "1.6.10"

repositories {

mavenCentral()

dependencies {

implementation("io.ktor:ktor-server-netty:1.6.10")

implementation("io.ktor:ktor-websockets:1.6.10")

1) Write Ktor Application Code: Create a new Kotlin file (e.g., PushNotificationServer.kt)
and write the Ktor application code:
2) Execute the main function in your PushNotificationServer.kt file. This will start the Ktor
server on http://localhost:8080.
3) Create an HTML file (e.g., index.html) with a simple WebSocket client: Open the
index.html file in a web browser. You can open multiple instances in different tabs or
browsers to simulate multiple clients.
4) Interact with the WebSocket: Type a message in one client and click "Send Message."
You should see the message pushed to all other connected clients in real-time.

57

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

58

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Program:

Kotlin:

import io.ktor.application.*

import io.ktor.features.ContentNegotiation

import io.ktor.features.StatusPages

import io.ktor.http.HttpStatusCode

import io.ktor.jackson.jackson

import io.ktor.routing.routing

import io.ktor.server.engine.embeddedServer

import io.ktor.server.netty.Netty

import io.ktor.websocket.WebSockets

import io.ktor.websocket.webSocket

import kotlinx.coroutines.channels.ClosedReceiveChannelException

import kotlinx.coroutines.channels.consumeEach

import java.time.Duration

fun Application.module() {

install(ContentNegotiation) {

jackson { }

install(StatusPages) {

exception<Throwable> { cause ->

call.respondText(cause.localizedMessage, status = HttpStatusCode.InternalServerError)

install(WebSockets) {

pingPeriod = Duration.ofSeconds(60)

59

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

60

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

timeout = Duration.ofSeconds(15)

maxFrameSize = Long.MAX_VALUE

masking = false

routing {

val connections = mutableListOf<DefaultWebSocketServerSession>()

webSocket("/push") {

connections.add(this)

try {

incoming.consumeEach { frame ->

if (frame is Frame.Text) {

val message = frame.readText()

connections.forEach {

if (it != this) {

it.send(Frame.Text(message))

} catch (e: ClosedReceiveChannelException) {

// Channel was closed normally

} finally {

connections.remove(this)

61

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

62

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

fun main() {

embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)

HTML file:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>WebSocket Push Notification</title>

</head>

<body>

<input type="text" id="messageInput" placeholder="Type a message">

<button onclick="sendMessage()">Send Message</button>

<ul id="messages"></ul>

<script>

const socket = new WebSocket("ws://localhost:8080/push");

socket.onmessage = (event) => {

const messages = document.getElementById("messages");

const li = document.createElement("li");

li.appendChild(document.createTextNode(event.data));

messages.appendChild(li);

};

63

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

64

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

function sendMessage() {

const input = document.getElementById("messageInput");

const message = input.value;

socket.send(message);

input.value = "";

</script>

</body>

</html>

65

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

66

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. What is the command or process to create a new Kotlin project?


2. How is WebSocket different from traditional HTTP?
3. Name one key module in Ktor for handling WebSocket connections.
4. Provide a simple example of JavaScript code for WebSocket communication on the
client side.
5. Name one security measure for securing WebSocket communication.

Postlab Questions:

1. What challenges might arise with a significant increase in WebSocket connections?


2. Give an example of a common error scenario in WebSocket communication.
3. How would you debug WebSocket connection issues in the server?
4. What factor is crucial for ensuring timely delivery of notifications to users?
5. Name one additional feature that could enhance the push notification system.

Results:

Thus the program to design a web server supporting push notifications has been executed
successfully.

67

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

68

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 9
Develop an application by integrating Google maps
Date:

Aim:

To develop an application by integrating Google maps

Procedure:

To integrate Google Maps into an Android application using Kotlin, you can follow these steps:

Get API Key:

Visit the Google Cloud Console.

Create a new project or select an existing one.

Enable the "Maps SDK for Android" for your project.

Create an API key.

Add Google Maps Dependency:

Open your app-level build.gradle file and add the Google Maps dependency:

gradle

implementation 'com.google.android.gms:play-services-maps:17.0.1'

Add Permissions:

Make sure you have the necessary permissions in your AndroidManifest.xml file:

xml

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

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

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

Add API Key:

Add your Google Maps API key to the AndroidManifest.xml file:

Xml

<application>

<!-- Other application elements -->

69

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

70

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

<meta-data

android:name="com.google.android.geo.API_KEY"

android:value="YOUR_API_KEY" />

</application>

Create a Map Fragment:

Create a layout file (fragment_map.xml) for the map fragment:

Xml

<!-- fragment_map.xml -->

<fragment

android:id="@+id/mapFragment"

android:name="com.google.android.gms.maps.SupportMapFragment"

android:layout_width="match_parent"

android:layout_height="match_parent" />

Initialize GoogleMap:

In your activity or fragment, initialize the GoogleMap object:

kotlin

import com.google.android.gms.maps.GoogleMap

import com.google.android.gms.maps.OnMapReadyCallback

import com.google.android.gms.maps.SupportMapFragment

class MapFragment : Fragment(R.layout.fragment_map), OnMapReadyCallback {

private lateinit var googleMap: GoogleMap

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

super.onViewCreated(view, savedInstanceState)

val mapFragment = childFragmentManager.findFragmentById(R.id.mapFragment) as


SupportMapFragment

mapFragment.getMapAsync(this)

71

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

72

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

override fun onMapReady(map: GoogleMap) {

googleMap = map

// Add your map configurations here

// For example: setMapType, addMarkers, etc.

Run the App:

Run your application on an emulator or a physical device to see the Google Map in action.

73

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

74

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Prelab Questions:

1. Why do you need an API key for integrating Google Maps into your Android application?
2. What is the purpose of adding com.google.android.gms:play-services-maps to your
project's dependencies?
3. Why are location-related permissions (ACCESS_FINE_LOCATION and
ACCESS_COARSE_LOCATION) essential in the AndroidManifest.xml file?
4. How does the SupportMapFragment contribute to the incorporation of Google Maps in
your Android app?
5. Where should you specify the Google Maps API key in the AndroidManifest.xml file?

Postlab Questions:

1. In which callback method do you initialize the GoogleMap object, and why is this crucial
for map-related operations?
2. What steps are involved in adding a marker to the Google Map, and what details can be
associated with a marker?
3. What is the purpose of the CameraUpdateFactory.newLatLngZoom method, and how
does it affect the camera position on the map?
4. Name two common customizations you can apply to the Google Map to enhance the
user experience.
5. What aspects should you focus on when testing your Google Maps integration, and why
is testing important?

Results:

Thus the program to develop an application by integrating Google maps has been executed
successfully.

75

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

76

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

Ex No: 10
Mini Projects involving Flutter/Kotlin multi-platform
Date:

Aim:

Mini Projects involving Flutter/Kotlin multi-platform

77

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

78

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

79

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

80

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

81

Downloaded by RISHIKESH KA CSE ([email protected])


lOMoARcPSD|37512785

82

Downloaded by RISHIKESH KA CSE ([email protected])

You might also like