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

Practicals

Practicals

Uploaded by

aatifnizami123
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)
5 views

Practicals

Practicals

Uploaded by

aatifnizami123
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
You are on page 1/ 42

Note : Write import code only in 1 practical

MCAD Practicals
1. Create “Hello World” application that displays “Hello World” in the
middle of the screen using Text View Widget in the red color.
//Full Practical

MainActivity.kt
package com.example.practical_1

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.ui.AppBarConfiguration
import com.example.practical_1.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

private lateinit var appBarConfiguration: AppBarConfiguration


private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

}
}
activity_main.xml
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textColor="#FF0000"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintLeft_toLeftOf="p
arent"
app:layout_constraintRight_toRightOf=
"parent"
app:layout_constraintTop_toTopOf="p
arent" />

</androidx.constraintlayout.widget.ConstraintLayout>

2. Create application for demonstration of activity life cycle.


// Write only Kotlin file

MainActvity.kt
package com.example.practical_2
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

showToast("onCreate")
}

override fun onStart() {


super.onStart()
showToast("onStart")
}
override fun onResume() {
super.onResume()
showToast("onResume")
}

override fun onPause() {


super.onPause()
showToast("onPause")
}

override fun onStop() {


super.onStop()
showToast("onStop")
}
override fun onDestroy() {
super.onDestroy()
showToast("onDestroy")
}

private fun showToast(message: String) {


Toast.makeText(this, "Activity Lifecycle: $message",
Toast.LENGTH_SHORT).show()
}
}
activity_main.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">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true"
android:onClick="onButtonClick" />
</RelativeLayout>

3. Create an application for demonstration of different Layouts.

//Write only xml file

MainActivity.kt
package com.example.practical_3

import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import com.example.practical_3.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

private lateinit var appBarConfiguration: AppBarConfiguration


private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/textViewLinear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout Example"
android:textSize="20sp"
android:layout_gravity="center"/>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/buttonRelative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Relative Layout Button"
android:layout_centerInParent="true"/>
</RelativeLayout>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textViewFrame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FrameLayout Example"
android:textSize="20sp"
android:layout_gravity="center"/>
</FrameLayout>

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/imageViewConstraint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonRelative"
app:layout_constraintBottom_toTopOf="@id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintVertical_bias="0.5"
tools:ignore="NotSibling"
app:tint="#333333" />

<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</LinearLayout>

4. Create an application that will get the text entered in Edit Text and
display that text using Toast (Message)

//only write onCreate method and toast method from Kotlin file and
also write xml file
MainActivity.kt
package com.example.practical_4

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val inputEditText: EditText = findViewById(R.id.inputEditText)


val showToastButton: Button = findViewById(R.id.showToastButton)

showToastButton.setOnClickListener(View.OnClickListener {
val userInput = inputEditText.text.toString()
showToast("You entered: $userInput")
})
}

private fun showToast(message: String) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}

Activity_main.xml
<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"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message"
android:layout_marginBottom="16dp"
android:inputType="text" />

<Button
android:id="@+id/showToastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"
android:layout_below="@id/inputEditText"
android:layout_centerHorizontal="true" />

</RelativeLayout>.
5. Create an application for demonstration of explicitly starting new
activity using Intent.

//write both kotlin file and in manifest.xml activity part


highlighted below in manifest file

MainActivity.kt
package com.example.practical_5

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class SecondActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
}
}
SecondActivity.kt
package com.example.practical_5
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val startSecondActivityButton: Button =


findViewById(R.id.startSecondActivityButton)

startSecondActivityButton.setOnClickListener(View.OnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
})
}
}
activity_main.xml
<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"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/startSecondActivityButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Second Activity"
android:layout_centerInParent="true" />

<TextView
android:id="@+id/displayText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the First activity!"
android:textSize="18sp"
android:textStyle="bold"
android:layout_centerInParent="true"
android:layout_above="@id/startSecondActivityButton" />

</RelativeLayout>
activity_second.xml
<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"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".SecondActivity">

<TextView
android:id="@+id/displayText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the second activity!"
android:textSize="18sp"
android:textStyle="bold"
android:layout_centerInParent="true" />

</RelativeLayout>

AndroidManifest.xml
<?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.Practical_5"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Practical_5">

<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:exported="true"
android:label="Practical_5_Second"
android:theme="@style/Theme.Practical_5">
</activity>
</application>

</manifest>

6. Create a registration page to demonstrate basic widgets available.\

// Full Practical

MainActivity.kt
package com.example.practical_6

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val editTextUsername: EditText =


findViewById(R.id.editTextUsername)
val editTextEmail: EditText = findViewById(R.id.editTextEmail)
val editTextPassword: EditText =
findViewById(R.id.editTextPassword)
val buttonRegister: Button = findViewById(R.id.buttonRegister)

buttonRegister.setOnClickListener {
val username = editTextUsername.text.toString()
val email = editTextEmail.text.toString()
val password = editTextPassword.text.toString()

val message = "Registration successful\nUsername:


$username\nEmail: $email\nPassword: $password"
showToast(message) } }
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
activity_main.xml
<LinearLayout
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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />

<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:inputType="textEmailAddress" />

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />

<Button
android:id="@+id/buttonRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register" />

</LinearLayout>
7. Create sample application with login module. (check username and
password). On successful login, change Text View “Login Successful”
and on failing login, alert user using Toast “Login failed”.
// Only Kotlin file

MainActivity.kt
package com.example.practical_7
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var usernameEditText: EditText


private lateinit var passwordEditText: EditText
private lateinit var resultTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

usernameEditText = findViewById(R.id.usernameEditText)
passwordEditText = findViewById(R.id.passwordEditText)
resultTextView = findViewById(R.id.resultTextView)
}

fun onLoginButtonClick(view: View) {


val username = usernameEditText.text.toString()
val password = passwordEditText.text.toString()

val correctUsername = "user123"


val correctPassword = "pass123"

if (username == correctUsername && password ==


correctPassword) {
resultTextView.text = "Login Successful"
} else {
resultTextView.text = ""
showToast("Login failed")
}
}

private fun showToast(message: String) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}

main_activity.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/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:layout_marginTop="100dp"
android:padding="10dp" />

<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"
android:layout_below="@id/usernameEditText"
android:layout_marginTop="20dp"
android:padding="10dp" />

<Button
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/passwordEditText"
android:layout_marginTop="20dp"
android:padding="10dp"
android:onClick="onLoginButtonClick" />

<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_below="@id/loginButton"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

</RelativeLayout>
8. Create login application where you will have to validate username
and password. Till the username and password is not validated, login
button should remain disabled.

//Only Kotlin
ActivityMain.kt
package com.example.practical_8

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


private lateinit var usernameEditText: EditText
private lateinit var passwordEditText: EditText
private lateinit var loginButton: Button

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

usernameEditText = findViewById(R.id.usernameEditText)
passwordEditText = findViewById(R.id.passwordEditText)
loginButton = findViewById(R.id.loginButton)

usernameEditText.addTextChangedListener(textWatcher)
passwordEditText.addTextChangedListener(textWatcher)
}

private val textWatcher = object : TextWatcher {


override fun beforeTextChanged(s: CharSequence?, start: Int, count:
Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before:
Int, count: Int) {}

override fun afterTextChanged(s: Editable?) {


val username = usernameEditText.text.toString().trim()
val password = passwordEditText.text.toString().trim()
loginButton.isEnabled = username.isNotEmpty() &&
password.isNotEmpty()
}
}
}

activity_main.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"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"/>

<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/usernameEditText"
android:layout_marginTop="16dp"
android:inputType="textPassword"
android:hint="Password"/>

<Button
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/passwordEditText"
android:layout_marginTop="16dp"
android:enabled="false"
android:text="Login"/>
</RelativeLayout>

9. Create a login application as above. Validate login data and display


error to user using setError() method.

//Only Kotlin
MainActivity.kt
package com.example.practical_9

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {

private lateinit var editTextUsername: EditText


private lateinit var editTextPassword: EditText
private lateinit var buttonLogin: Button

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

editTextUsername = findViewById(R.id.editTextUsername)
editTextPassword = findViewById(R.id.editTextPassword)
buttonLogin = findViewById(R.id.buttonLogin)

buttonLogin.setOnClickListener {
validateCredentials()
}
}

private fun validateCredentials() {


val username = editTextUsername.text.toString()
val password = editTextPassword.text.toString()

if (username.isEmpty()) {
editTextUsername.setError("Username cannot be empty")
return
}
if (password.isEmpty()) {
editTextPassword.setError("Password cannot be empty")
return
}
showMessage("Login successful")
}
private fun showMessage(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"/>

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_marginTop="8dp"
android:hint="Password"/>

<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"/>
</LinearLayout>
10. Create an application that will pass two numbers using Text View to
the next screen, and on the next screen display sum of those numbers.

//Only Kotlin
MainActivity.kt
package com.example.practical_10

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


private lateinit var btnCalculate: Button
private lateinit var editTextNumber1: EditText
private lateinit var editTextNumber2: EditText

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Find views by their IDs


btnCalculate = findViewById(R.id.btnCalculate)
editTextNumber1 = findViewById(R.id.editTextNumber1)
editTextNumber2 = findViewById(R.id.editTextNumber2)

// Set click listener for the button


btnCalculate.setOnClickListener {
val number1 = editTextNumber1.text.toString().toDoubleOrNull() ?:
0.0
val number2 = editTextNumber2.text.toString().toDoubleOrNull() ?:
0.0
val intent = Intent(this, ResultActivity::class.java)
intent.putExtra("number1", number1)
intent.putExtra("number2", number2)
startActivity(intent)
}
}
}
ResultActivity.kt
package com.example.practical_10
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class ResultActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)

val number1 = intent.getDoubleExtra("number1", 0.0)


val number2 = intent.getDoubleExtra("number2", 0.0)
val sum = number1 + number2

// Find the TextView and set its text


val textViewResult: TextView = findViewById(R.id.textViewResult)
textViewResult.text = "Sum: $sum"
}
}
activity_main.xml
<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/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter Number 1"
android:inputType="numberDecimal"/>
<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber1"
android:layout_marginTop="16dp"
android:hint="Enter Number 2"
android:inputType="numberDecimal"/>

<Button
android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber2"
android:layout_marginTop="16dp"
android:text="Calculate"/>
</RelativeLayout>
activity_result.kt
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Result"/>

</RelativeLayout>
AndroidManifest.xml
<?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.Practical_10"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Practical_10">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity
android:name=".ResultActivity"
android:exported="true"
android:label="Practical_10"
android:theme="@style/Theme.Practical_10">
</activity>
</application>

</manifest>
11. Create an application to demonstrate different Animations.

//Full Practical

MainActivity.kt
package com.example.practical_12
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val btnFadeIn: Button = findViewById(R.id.btnFadeIn)


val btnRotate: Button = findViewById(R.id.btnRotate)

btnFadeIn.setOnClickListener {
val fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in)
findViewById<View>(android.R.id.content).startAnimation(fadeIn)
}
btnRotate.setOnClickListener {
val rotate = AnimationUtils.loadAnimation(this, R.anim.rotate)
findViewById<View>(android.R.id.content).startAnimation(rotate)
}
}
}
activity_main.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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:id="@+id/btnFadeIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade In"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>

<Button
android:id="@+id/btnRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate"
android:layout_below="@id/btnFadeIn"
android:layout_marginTop="20dp"/>

</RelativeLayout>
fade_in.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromAlpha="0.0"
android:toAlpha="1.0"/>
rotate.xml
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%" />
12 Create an application to demonstrate use of Media Player.

//Only Kotlin
ActivityMain.kt
package com.example.practical_13
import android.media.MediaPlayer
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var mediaPlayer: MediaPlayer


private lateinit var btnPlay: Button

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

mediaPlayer = MediaPlayer.create(this, R.raw.sample)


btnPlay = findViewById(R.id.btnPlay)

btnPlay.setOnClickListener {
if (mediaPlayer.isPlaying) {
mediaPlayer.pause()
btnPlay.text = "Play"
} else {
mediaPlayer.start()
btnPlay.text = "Pause"
}
}
}
override fun onDestroy() {
super.onDestroy()
mediaPlayer.release()
}
}

activity_main.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">
<Button
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Play" />
</RelativeLayout>

13.Create an application to manage Student Data in the Device.


// Only Kotlin

ActivityMain.kt
package com.example.practical_14
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val studentDetailsTextView: TextView =


findViewById(R.id.studentDetailsTextView)
val studentNameTextView: TextView =
findViewById(R.id.studentNameTextView)
val studentRollNumberTextView: TextView =
findViewById(R.id.studentRollNumberTextView)

val studentName = "User 2005"


val studentRollNumber = "12345"

studentDetailsTextView.text = "Student Details"


studentNameTextView.text = "Name: $studentName"
studentRollNumberTextView.text = "Roll Number:
$studentRollNumber"
}
}

activity_main.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"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/studentDetailsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Details"
android:textSize="20sp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"/>

<TextView
android:id="@+id/studentNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: John Doe"
android:layout_below="@id/studentDetailsTextView"
android:layout_marginTop="20dp"/>

<TextView
android:id="@+id/studentRollNumberTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Roll Number: 12345"
android:layout_below="@id/studentNameTextView"
android:layout_marginTop="10dp"/>

</RelativeLayout>

14.Create an application to manage Student Data using Web Services.

// Only Kotlin and one line in android.manifest xml highlighted below

ActivityMain.kt
package com.example.practical_15

package com.example.test

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import android.widget.TextView

class MainActivity : AppCompatActivity() {


private lateinit var textView: TextView

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView)

fetchDataFromWebService("https://jsonplaceholder.typicode.com/users")
}

private fun fetchDataFromWebService(urlString: String) {


MainScope().launch(Dispatchers.IO) {
val result = makeHttpRequest(urlString)
result?.let {
val userData = parseUserData(result)
withContext(Dispatchers.Main) {
// Update the TextView with the fetched data
textView.text = userData.joinToString("\n")
}
}
}
}

private suspend fun makeHttpRequest(urlString: String): String? {


var connection: HttpURLConnection? = null
return try {
val url = URL(urlString)
connection = url.openConnection() as HttpURLConnection
val reader =
BufferedReader(InputStreamReader(connection.inputStream))
val response = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
response.append(line)
}
response.toString()
} finally {
connection?.disconnect()
}
}

private fun parseUserData(jsonString: String): List<String> {


val users = mutableListOf<String>()
val jsonArray = JSONArray(jsonString)
for (i in 0 until jsonArray.length()) {
val userObject = jsonArray.getJSONObject(i)
val user = "ID: ${userObject.getString("id")}, Name:
${userObject.getString("name")}, Email: ${userObject.getString("email")}"
users.add(user)
}
return users
}
}
activity_main.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"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Data"
android:textSize="24sp"
android:gravity="center"
android:layout_centerInParent="true"/>

</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.practical_15">

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


<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.Practical_15"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="false"
android:label="@string/app_name"
android:theme="@style/Theme.Practical_15">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

15.Create an application for calculator.

//Only Kotlin

MainActivity.kt
package com.example.practical_16

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import net.objecthunter.exp4j.ExpressionBuilder
import android.text.Editable
class MainActivity : AppCompatActivity() {

private lateinit var displayEditText: EditText


private var lastNumeric = false
private var lastDot = false

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

displayEditText = findViewById(R.id.displayEditText)
}

fun onDigitClick(view: View) {


val button = view as Button
displayEditText.append(button.text)
lastNumeric = true
}

fun onOperatorClick(view: View) {


if (lastNumeric && !isOperatorAdded(displayEditText.text.toString()))
{
val button = view as Button
displayEditText.append(button.text)
lastNumeric = false
lastDot = false
}
}

fun onDecimalClick(view: View) {


if (lastNumeric && !lastDot) {
displayEditText.append(".")
lastNumeric = false
lastDot = true
}
}

fun onClearClick(view: View) {


displayEditText.text = Editable.Factory.getInstance().newEditable("")
lastNumeric = false
lastDot = false
}

fun onEqualClick(view: View) {


try {
val expression =
ExpressionBuilder(displayEditText.text.toString()).build()
val result = expression.evaluate()
displayEditText.text.clear()
displayEditText.append(result.toString())
lastDot = result % 1 != 0.0
} catch (e: Exception) {
displayEditText.text =
Editable.Factory.getInstance().newEditable("Error")
}
}

private fun isOperatorAdded(value: String): Boolean {


return if (value.isNotEmpty()) {
val lastChar = value[value.length - 1]
lastChar == '+' || lastChar == '-' || lastChar == '*' || lastChar == '/'
} else {
false
}
}
}

activity_main.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"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/displayEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="none"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp" />

<GridLayout
android:id="@+id/calculatorButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/displayEditText"
android:columnCount="4"
android:rowCount="5"
android:layout_marginTop="16dp">

<Button
android:id="@+id/btn_clear"
android:text="C"
android:onClick="onClearClick" />

<Button
android:id="@+id/btn_divide"
android:text="/"
android:onClick="onOperatorClick" />

<Button
android:id="@+id/btn_multiply"
android:text="*"
android:onClick="onOperatorClick" />

<Button
android:id="@+id/btn_minus"
android:text="-"
android:onClick="onOperatorClick" />

<Button
android:id="@+id/btn_7"
android:text="7"
android:onClick="onDigitClick" />
<Button
android:id="@+id/btn_8"
android:text="8"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_9"
android:text="9"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_plus"
android:text="+"
android:onClick="onOperatorClick" />

<Button
android:id="@+id/btn_4"
android:text="4"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_5"
android:text="5"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_6"
android:text="6"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_equal"
android:text="="
android:layout_rowSpan="2"
android:onClick="onEqualClick" />

<Button
android:id="@+id/btn_1"
android:text="1"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_2"
android:text="2"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_3"
android:text="3"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_0"
android:text="0"
android:layout_columnSpan="2"
android:onClick="onDigitClick" />

<Button
android:id="@+id/btn_dot"
android:text="."
android:onClick="onDecimalClick" />

</GridLayout>

</RelativeLayout>

16.Create an application for distance and weight converters.


//Only Kotlin and strings.xml

MainActivity.kt
package com.example.practical_17

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var editTextValue: EditText


private lateinit var spinnerFrom: Spinner
private lateinit var btnConvert: Button
private lateinit var textViewResult: TextView

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

editTextValue = findViewById(R.id.editTextValue)
spinnerFrom = findViewById(R.id.spinnerFrom)
btnConvert = findViewById(R.id.btnConvert)
textViewResult = findViewById(R.id.textViewResult)

val units = arrayOf("Meters", "Kilometers", "Miles", "Pounds",


"Kilograms")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item,
units)

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropd
own_item)
spinnerFrom.adapter = adapter

btnConvert.setOnClickListener {
convertValue()
}

spinnerFrom.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onItemSelected(parentView: AdapterView<*>?,
selectedItemView: View?, position: Int, id: Long) {
}

override fun onNothingSelected(parentView: AdapterView<*>?) {


}
}
}

private fun convertValue() {


val inputValue = editTextValue.text.toString().toDoubleOrNull()
if (inputValue != null) {
val selectedUnit = spinnerFrom.selectedItemPosition

val result = when (selectedUnit) {


a. -> convertMetersToKilometers(inputValue)
b.-> convertKilometersToMiles(inputValue)
c. -> convertMilesToMeters(inputValue)
d.-> convertPoundsToKilograms(inputValue)
e. -> convertKilogramsToPounds(inputValue)
else -> 0.0
}

textViewResult.text = getString(R.string.result_format, result)


} else {
textViewResult.text = getString(R.string.invalid_input)
}
}

private fun convertMetersToKilometers(meters: Double): Double {


return meters / 1000.0
}

private fun convertKilometersToMiles(kilometers: Double): Double {


return kilometers * 0.621371
}

private fun convertMilesToMeters(miles: Double): Double {


return miles * 1609.34
}

private fun convertPoundsToKilograms(pounds: Double): Double {


return pounds * 0.453592
}

private fun convertKilogramsToPounds(kilograms: Double): Double {


return kilograms * 2.20462
}
}

main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Value" />

<Spinner
android:id="@+id/spinnerFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/>

<Button
android:id="@+id/btnConvert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Convert"
android:layout_marginTop="16dp"/>

<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/>
</LinearLayout>
strings.xml
<resources>
<string name="app_name">Practical19</string>
<string name="input_value_hint">Enter a value</string>
<string name="convert_button_text">Convert</string>
<string name="result_format">Result: %.2f</string>
<string name="invalid_input">Invalid input. Please enter a valid
number.</string>
<string name="next">Next</string>
<string name="lorem_ipsum">Lorem Ipsum</string>
<string name="previous">Previous</string>
<string name="action_settings">Settings</string>
<string name="first_fragment_label">First Fragment</string>
<string name="second_fragment_label">Second Fragment</string>
</resources>

You might also like