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

APP Practical Journal-1

The document is a certification for a student who has completed practical work in Android Programming as part of their T.Y.B.Sc. (Information Technology) course at Vikas College of Arts, Science & Commerce. It includes a detailed index of practical exercises covering various aspects of Android development, such as creating projects, using Android Studio, and implementing components like activities, services, and broadcast receivers. Additionally, it contains code snippets and XML layouts demonstrating practical implementations in Android programming.

Uploaded by

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

APP Practical Journal-1

The document is a certification for a student who has completed practical work in Android Programming as part of their T.Y.B.Sc. (Information Technology) course at Vikas College of Arts, Science & Commerce. It includes a detailed index of practical exercises covering various aspects of Android development, such as creating projects, using Android Studio, and implementing components like activities, services, and broadcast receivers. Additionally, it contains code snippets and XML layouts demonstrating practical implementations in Android programming.

Uploaded by

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

Android Programming

Practical
VidyaVikas Education Society’s

VIKAS COLLEGE OF ARTS, SCIENCE & COMMERCE


Affiliated to University of Mumbai
RE-ACCREDITED ‘A’ GRADE BY NAAC
ISO 9001 : 2008 CERTIFIED
–––––
Vikas High School Marg, Kannamwar Nagar No 2, Vikhroli (E), Mumbai – 400083

Dr. R. K. Patra Hon’ ble: Shri P. M. Raut


Principal Chairman. V. V. Edu. Society

This is to certify that ,

a student of T.Y.B.Sc. (Information Technology) (Semester VI) with college-enrolled


Roll No.
/ University Seat No. ,

has satisfactorily completed the practical work for the subject Android Programming
Practical in the Information Technology program from the University of Mumbai
for the academic year 2024-2025.

Guided By College Seal Head Of Department


Prof. Abhishek Singh DR. Seema Rahul

External Examiner
INDEX

Sr Name of practical Pg.no Signature


Introduction to Android, Introduction to Android Studio IDE, Application
1 Fundamentals: Creating a Project, Android Components, Activities,
Services, Content Providers, Broadcast Receivers, Interface overview,
Creating Android Virtual device, USB debugging mode, Android
Application Overview. Simple “Hello World” program.
Programming Resources Android Resources: (Color, Theme, String,
2 Drawable, Dimension, Image)

Programming Activities and fragments Activity Life Cycle, Activity


3 methods, Multiple Activities, Life Cycle of fragments and multiple
fragments.

Programs related to different Layouts Coordinate, Linear, Relative, Table,


4 Absolute, Frame, List View, Grid View.

Programming UI elements AppBar, Fragments, UI Components


5
5 Programming menus, dialog, dialog fragments
6
Programs on Intents, Events, Listeners and Adapters The Android Intent
7 Class, Using Events and Event Listeners

Programs on Services, notification and broadcast receivers


8
PRACTICAL NO: 1

Aim: Introduction to Android, Introduction to Android Studio IDE, Application Fundamentals:


Creating a Project, Android Components, Activities, Services, Content Providers, Broadcast
Receivers, Interface overview, Creating Android Virtual device, USB debugging mode,
Android Application Overview. Simple “Hello World” program.
Solution:
Creating a project:
MainActivity.Kt :

package com.example.myapplication1
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import
androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

}
}

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:id="@+id/main"
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!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
APK in avd:

BroadcastActivity:

How to receiving Broadcast

Apps can receive and android BroadcastReceiver in two ways: through manifest-declared
receivers and context-registered receivers. In this example, we are approaching manifest-
declared Receiver. Learn step by step to the kotlin broadcast receiver example works.

Step 1. Create an android app, For creating an Android app with kotlin read this tutorial.

Step 2. Creating Broadcast Receiver

Create and extend Subclass and BroadcastReceiver implement. onReceive(Context, Intent)


where onReceive method each message is received as an Intent object parameter.

MainActivity.kt:

package com.example.myapplication8

import android.content.BroadcastReceiver import


android.content.Context import
android.content.Intent import android.os.Bundle
import android.widget.Toast import
androidx.activity.enableEdgeToEdge import
androidx.appcompat.app.AppCompatActivity
import android.content.IntentFilter

class MainActivity : AppCompatActivity() {


private lateinit var airplaneModeReceiver:
BroadcastReceiver override fun
onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main) airplaneModeReceiver =
object : BroadcastReceiver() { override fun onReceive(context:
Context?, intent: Intent?) { if (intent?.action ==
Intent.ACTION_AIRPLANE_MODE_CHANGED) { val
isAirplaneModeOn = intent.getBooleanExtra("state", false) if
(isAirplaneModeOn) {
Toast.makeText(context, "Airplane Mode Enabled",
Toast.LENGTH_SHORT).show()

} else {
Toast.makeText(context, "Airplane Mode Disabled",
Toast.LENGTH_SHORT).show()
}

}
}

}
// Register Broadcast Receiver val filter =
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)
registerReceiver(airplaneModeReceiver, filter)
}

override fun onDestroy() {


super.onDestroy()
unregisterReceiver(airplaneModeReceiver) // Unregister receiver when activity is
destroyed

broadcast.kt: package
com.example.myapplication8 import
android.content.BroadcastReceiver import
android.content.Context import
android.content.Intent import
android.widget.Toast class broadcast :
BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { if
(intent?.action == Intent.ACTION_AIRPLANE_MODE_CHANGED) {
val isAirplaneModeOn = intent.getBooleanExtra("state", false) if
(isAirplaneModeOn) {
Toast.makeText(context, "Airplane Mode Enabled",
Toast.LENGTH_SHORT).show()
} else {

Toast.makeText(context, "Airplane Mode Disabled",


Toast.LENGTH_SHORT).show()
}
}

}
}

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.MyApplication8"
tools:targetApi="31">

<!-- Register Main Activity -->


<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Register Broadcast Receiver -->
<receiver android:name=".broadcast"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>

</intent-filter>
</receiver>

</application>

</manifest>
Output:

Create and manage virtual devices:

To open the AVD Manager, do one of the following:


• Select Tools > AVD Manager.

• Click AVD Manager AVD Manager icon in the toolbar


.
PRACTICAL NO: 02
Aim: Programming Resources
Android Resources: (Color, Theme, String, Drawable, Dimension, Image)
Color:

Color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>
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:id="@+id/main"
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="colorPrimary"
android:textColor="@color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.481"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.424" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="colorAccent"
android:textColor="@color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.348" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="colorPrimaryDark"
android:textColor="@color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.272" />
</androidx.constraintlayout.widget.ConstraintLayout>

Main_Activity.Kt
package com.example.myapplication1
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import
androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

}
}
APK in avd:
Theme:

Style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
APK in avd:
String:

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:id="@+id/main"
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="@string/error"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.348" />
</androidx.constraintlayout.widget.ConstraintLayout>
String.xml:
<resources>
<string name="app_name">My Application1</string>
<string name="error">it may contain error</string>
</resources>

APK in avd:
Drawable:

1. Right click on drawable folder

2. Copy the image if you want to create image drawable

3. Paste that image file inside the drawable folder


MainActivity.kt
package com.example.myapplication1
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import
androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat import
androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(find
ViewById(R.id.main)) { v, insets -> val
systemBars =
insets.getInsets(WindowInsetsCompat.Type.systemB
ars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

}
}

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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@drawable/pand">
</LinearLayout>
APK in avd:
PRACTICAL NO:03

Aim: Programs related to different Layouts Coordinate, Linear, Relative, Table, Absolute, Frame, List
View, Grid View.
1. linear layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" > <Button
android:id="@+id/btnStartService" android:layout_width="270dp"
android:layout_height="wrap_content" android:text="start_service"/>
<Button
android:id="@+id/btnPauseService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="pause_service"/> <Button
android:id="@+id/btnStopService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="stop_service"/>
</LinearLayout>
Output:
2. Relative:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:paddingLeft="16dp" android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_cont
ent"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/name">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2" />
</LinearLayout>
</RelativeLayout>
Output:

3. Table:

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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TableLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="150dp">
<TableRow>
<Button
android:id="@+id/btn1"
android:text="1"
android:layout_gravity="center"
/>
<Button
android:id="@+id/btn2"
android:text="2"
android:layout_gravity="center"
/>
<Button
android:id="@+id/btn3"
android:text="3"
android:layout_gravity="center"
/>
</TableRow>
<TableRow>
<Button
android:id="@+id/btn4"
android:text="4"
android:layout_gravity="center"
/> <Button
android:id="@+id/btn5"
android:text="5"
android:layout_gravity="center"
/><Button
android:id="@+id/btn6"
android:text="6"
android:layout_gravity="center"
/>
</TableRow>
<TableRow>
<Button
android:id="@+id/btn7"
android:text="7"
android:layout_gravity="center"
/>
<Button
android:id="@+id/btn8"
android:text="8"
android:layout_gravity="center"
/><Button
android:id="@+id/btn9"
android:text="9"
android:layout_gravity="center"
/>
</TableRow>
</TableLayout>
</LinearLayout>

MainActivity.Kt:
com.example.myapplication1
import android.os.Bundle import
android.widget.Button import
android.widget.Toast import
androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val btn1: Button = findViewById(R.id.btn1)
val btn2: Button = findViewById(R.id.btn2)
val btn3: Button = findViewById(R.id.btn3)
val btn4: Button = findViewById(R.id.btn4)
val btn5: Button = findViewById(R.id.btn5)
val btn6: Button = findViewById(R.id.btn6)
val btn7: Button = findViewById(R.id.btn7)
val btn8: Button = findViewById(R.id.btn8)
val btn9: Button = findViewById(R.id.btn9)
btn1.setOnClickListener {
Toast.makeText(this, "Clicked 1", Toast.LENGTH_SHORT).show()
}
btn2.setOnClickListener {
Toast.makeText(this, "Clicked 2", Toast.LENGTH_SHORT).show()
}
btn3.setOnClickListener {
Toast.makeText(this, "Clicked 3", Toast.LENGTH_SHORT).show()
}
btn4.setOnClickListener {
Toast.makeText(this, "Clicked 4", Toast.LENGTH_SHORT).show()
}
btn5.setOnClickListener {
Toast.makeText(this, "Clicked 5", Toast.LENGTH_SHORT).show()
}
btn6.setOnClickListener {
Toast.makeText(this, "Clicked 6", Toast.LENGTH_SHORT).show()
}
btn7.setOnClickListener {
Toast.makeText(this, "Clicked 7", Toast.LENGTH_SHORT).show()
}
btn8.setOnClickListener {
Toast.makeText(this, "Clicked 8", Toast.LENGTH_SHORT).show()
}
btn9.setOnClickListener {
Toast.makeText(this, "Clicked 9", Toast.LENGTH_SHORT).show()
}
}
}
Output:

5. List View:
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:layout_gravity="center"
android:layout_marginLeft="150dp"
android:text="open ListView"/> </LinearLayout>

MainActivity.Kt
package com.example.myapplication1
import android.content.Intent import
android.os.Bundle import
android.widget.Button import
android.widget.Toast import
androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main) val
btn: Button = findViewById(R.id.btn)
btn.setOnClickListener { val intent =
Intent(this, List_view::class.java)
startActivity(intent)
}
}
}
String.xml:
<resources>
<string name="app_name">My Application1</string>
<array name="insert_list">
<item>one</item>
<item>two</item>
<item>three</item>
<item>four</item>
<item>five</item>
<item>six</item>
<item>seven</item>
<item>eight</item>
<item>nine</item>
<item>ten</item>
</array>
</resources>

Activity_list_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android
" xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".List_view"
android:entries="@array/insert_list"> </ListView>

List_view.kt:
package com.example.myapplication1
import android.os.Bundle import
androidx.activity.enableEdgeToEdge import
androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class List_view : AppCompatActivity() { override
fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_list_view)
}
}

Output:
6. Grid layout:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/andr
oid" xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" android:rowCount="3"
android:columnCount="3" android:padding="20dp">
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="1"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="2"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp“
android:text="3"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="4"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="5"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="6"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="7"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="8"/>
<Button
android:layout_width="110
dp"
android:layout_height="100
dp" android:text="9"/>
</GridLayout>

Output:
PRACTICAL NO: 04
Aim: Programming UI elements
AppBar, Fragments, UI Components

Design App With UI:


mainActivity.kt:
package com.example.myapplication1
import android.content.Intent import
android.os.Bundle import
android.widget.Button import
android.widget.Toast import
androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
}
}

String.xml:
<resources>
<color name="colorPrimary">#008577</color>
</resources>
activity_main.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:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="@drawable/backgrd">
<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="208dp"
android:layout_marginTop="100dp"
app:srcCompat="@drawable/captureing" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:alpha="0.7"
android:text="Welcome"
android:textColor="#000000"
android:textSize="33dp"
android:textStyle="bold" />
<Button android:id="@+id/login"
android:layout_width="258dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:alpha="0.8"
android:backgroundTint="@color/colorPrimary"
android:text="Login"
android:textStyle="bold" />
<Button android:id="@+id/newaccount"
android:layout_width="261dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:alpha="0.8"
android:backgroundTint="@color/colorPrimary"
android:text="REGISTER"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>

Output:
PRACTICAL NO:05

Aim: Programming menus, dialog, dialog fragments


Activity_main.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:gravity="center_horizontal" android:orientation="vertical"
tools:context=".MainActivity"
>
<TextView
android:id="@+id/textView"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:text="Hello World" />
</LinearLayout>

MainActivity.kt:
package com.example.myapplication1 import
android.os.Bundle import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import
androidx.appcompat.app.AppCompatActivity
import java.lang.Override as Override1
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
}
override fun onBackPressed() {
showExitDialog()
}
private fun showExitDialog() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Alert")
builder.setMessage("Are you sure you want to exit?")

builder.setPositiveButton("Yes") { _, _ ->
finish() // Closes the activity (exit app)
}
builder.setNegativeButton("No") { dialog, _ ->
dialog.dismiss() // Dismiss the dialog
}
val alertDialog = builder.create()
alertDialog.show()
}
}
Output:
menu
1. To create menu.xml right click on res folder
2. click on new resource file .

3. know right click on menu folder select menu resourse file.

4. double click on menu.xml drag and drop menu items


Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Item1"
android:id="@+id/item1"/>
<item android:title="Item2"
android:id="@+id/item2"/>
<item android:title="Item3"
android:id="@+id/item3"/>
<item android:title="Item4"
android:id="@+id/item4"/>
</menu>
MainActivity.xml:
package com.example.myapplication1
import android.os.Bundle import
android.view.Menu import
android.view.MenuItem import
android.widget.Toast import
androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu):
Boolean { menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.item1 -> {
Toast.makeText(this, "Item 1 is selected", Toast.LENGTH_SHORT).show()
return true
}
R.id.item2 -> {
Toast.makeText(this, "Item 2 is selected", Toast.LENGTH_SHORT).show()
return true
}
R.id.item3 -> {
Toast.makeText(this, "Item 3 is selected", Toast.LENGTH_SHORT).show()
return true
}
R.id.item4 -> {
Toast.makeText(this, "Item 4 is selected", Toast.LENGTH_SHORT).show()
return true
}
else -> return super.onOptionsItemSelected(item) }}}

Output:
PRACTICAL NO:06

Aim: Programs on Intents, Events, Listeners and Adapters


The Android Intent Class, Using Events and Event Listeners
activity_main.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical"
android:gravity="center" android:padding="20dp">
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:padding="10dp"/>
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_marginTop="20dp"/>
</LinearLayout>

MainActivity.kt
com.example.myapp
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import
android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val etName: EditText = findViewById(R.id.etName)
val btnSubmit: Button = findViewById(R.id.btnSubmit)
btnSubmit.setOnClickListener {
val name = etName.text.toString()
if (name.isNotEmpty()) { val intent = Intent(this,
SecondActivity::class.java) intent.putExtra("USER_NAME", name) //
Passing the name to second activity
startActivity(intent)
} else {
etName.error = "Please enter your name"
}
}
}
}

activity_second.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical"
android:gravity="center" android:padding="20dp">
<TextView
android:id="@+id/tvWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"/>
</LinearLayout>

SecondActivity.kt
com.example.myapp
import android.os.Bundle
import
android.widget.TextView
import
androidx.appcompat.app.App
CompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val tvWelcome: TextView = findViewById(R.id.tvWelcome)
// Receiving data from MainActivity val
name = intent.getStringExtra("USER_NAME")
tvWelcome.text = "Hello, $name!"
}

Output:
PRACTICAL NO:07

Aim: Programs on Services, notification, and broadcast receivers


1. Programs on Services:
Services are commands which are used by kotlin in functions to execute the task. They are
:IntentService, onStartCommand(),onHandleIntent() etc.
2. notification and broadcast receivers:
Step 1. Create an android app, For creating an Android app with kotlin read this tutorial.
Step 2. Creating Broadcast Receiver Create and extend Subclass and
BroadcastReceiverimplement.onReceive(Context, Intent) where onReceive method each message
is received as an Intent object parameter.

1. Notification:
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">
<!-- Permission for Notifications (Required for Android 13+) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<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.MyApplication9"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

MainActivit.kt
package com.example.myapplication9
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context import
android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import
androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat import
androidx.core.app.NotificationCompat import
androidx.core.app.NotificationManagerCompat
import com.example.myapplication9.R
class MainActivity :
AppCompatActivity() { private val
CHANNEL_ID = "123" private val
NOTIFICATION_ID_1 = 111
private val REQUEST_CODE_NOTIFICATIONS = 101
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createNotificationChannel()
// Check and request notification permission for Android 13+ if
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if
(checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
REQUEST_CODE_NOTIFICATIONS)
}
}
}
private fun createNotificationChannel() { if
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID, "Notification Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
}
fun show1(view: View) {
// Check if permission is granted before sending the
notification if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
return // Exit if permission is not granted
}
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground) // Ensure this icon exists
.setContentTitle("First Notification")
.setContentText("This notification is not clickable.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID_1, notification)
}
}

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">
<Button android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification 1"
android:layout_alignParentTop="true"
android:layout_marginTop="133dp"
android:onClick="show1"
android:layout_centerInParent="true"/>
<Button android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification 2"
android:layout_marginTop="156dp"
android:layout_below="@+id/btn1"
android:onClick="show2"
android:layout_centerInParent="true"/> </RelativeLayout>

Output:
Broadcast Receivers in Android
A Broadcast Receiver listens for system-wide and custom broadcasts. 3.1 Creating a
Broadcast
Receiver for Airplane Mode
1. Create MyBroadcastReceiver.kt Kotlin class MyBroadcastReceiver :
BroadcastReceiver() { override fun onReceive(context: Context, intent:
Intent) { if (intent.action ==
Intent.ACTION_AIRPLANE_MODE_CHANGED)
{
val isAirplaneModeOn = intent.getBooleanExtra("state", false) Toast.makeText(context,
"Airplane Mode: $isAirplaneModeOn", Toast.LENGTH_SHORT).show()
}
}}
2. Register Receiver in AndroidManifest.xml
3.2 Sending and Receiving Custom
Broadcast 1. Create MyCustomReceiver.kt
kotlin
class MyCustomReceiver : BroadcastReceiver()
{ override fun onReceive(context: Context, intent:
Intent)
{
val message = intent.getStringExtra("message") Toast.makeText(context, "Received:
$message" , Toast.LENGTH_SHORT).show()
}
} 2. Register Receiver in AndroidManifest.xml
xml 3. Send Broadcast (MainActivity.kt) kotlin
val intent
=Intent("com.example.CUSTOM_BROADCAST") intent.putExtra("message", "Hello
from MainActivity") sendBroadcast(intent)
PRACTICAL NO:08

Aim: Database Programming with SQLite


MainActivit,kt
package com.example.myapplication9
import android.database.Cursor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import
android.widget.EditText
import
android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var dbHelper: DatabaseHelper
lateinit var etName: EditText
lateinit var tvResult: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbHelper = DatabaseHelper(this) etName =
findViewById(R.id.etName) val btnSave =
findViewById<Button>(R.id.btnSave) val
btnShow = findViewById<Button>(R.id.btnShow)
tvResult = findViewById(R.id.tvResult)
// Save Name Button Click
btnSave.setOnClickListener {
val name = etName.text.toString()
if (name.isNotEmpty()) { val
success = dbHelper.insertUser(name)
if (success) {
Toast.makeText(this, "Name Saved!", Toast.LENGTH_SHORT).show()
etName.text.clear()
} else {
Toast.makeText(this, "Error Saving Name!", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Enter a Name!", Toast.LENGTH_SHORT).show()
}

}
// Show Names Button Click
btnShow.setOnClickListener { val
cursor: Cursor = dbHelper.getUsers()
val stringBuilder = StringBuilder()
if (cursor.count == 0) {
tvResult.text = "No Names Found!"
return@setOnClickListener
}
while (cursor.moveToNext()) {
stringBuilder.append("ID: ${cursor.getInt(0)}\n")
stringBuilder.append("Name: ${cursor.getString(1)}\n\n")
} cursor.close()
tvResult.text = stringBuilder.toString()
}
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical"
android:padding="20dp">
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="@+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Name" />
<Button
android:id="@+id/btnShow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Names" />
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saved Names"
android:textSize="16sp"
android:paddingTop="10dp" />
</LinearLayout>

DatabaseHelper.kt
com.example.myapplication9
import
android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, "UserDB", null, 1) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE Users (id INTEGER PRIMARY KEY
AUTOINCREMENT, name TEXT)")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS Users")
onCreate(db)
}
// Add User
fun insertUser(name: String):
Boolean { val db =
writableDatabase val values =
ContentValues()
values.put("name", name)
val result = db.insert("Users", null,
values) db.close() return result !=
-1L
}
// Get Users fun
getUsers(): Cursor { val
db = readableDatabase
return db.rawQuery("SELECT * FROM Users", null)

}
}
Output

You might also like