0% found this document useful (0 votes)
2 views28 pages

Mobile Application Development

The document provides a comprehensive guide on various Android development concepts including Intent for navigation, AlertDialog for pop-up messages, and SharedPreferences for data storage. It outlines specific coding examples and memory tricks to help developers remember key functionalities such as creating menus, notifications, and handling user location. Additionally, it categorizes notifications into types and explains the use of Context in Android applications.

Uploaded by

student -1
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)
2 views28 pages

Mobile Application Development

The document provides a comprehensive guide on various Android development concepts including Intent for navigation, AlertDialog for pop-up messages, and SharedPreferences for data storage. It outlines specific coding examples and memory tricks to help developers remember key functionalities such as creating menus, notifications, and handling user location. Additionally, it categorizes notifications into types and explains the use of Context in Android applications.

Uploaded by

student -1
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/ 28

26 February 2025 17:14

If the name... It’s a... Example


Ends in "-Manager", "-Helper", "- ✅ Class NotificationManager, SQLiteOpenHelper,
Utils" TextUtils
Ends in "-Listener", "-Callback" ✅ Interface OnClickListener, LocationCallback
Ends in "-Dialog" or "-Builder" ✅ Class AlertDialog, AlertDialog.Builder
Starts with "get", "set", "start", ✅ Method startActivity(), show(), getSharedPreferences()
"show"

Intent (For Navigation)


• If it’s Explicit (Opening another activity)

val intent = Intent(this, NextActivity::class.java)


startActivity(intent)
• If it’s Implicit (Opening a URL, Call, etc.)

val intent = Intent(Intent.ACTION_VIEW, Uri.parse("<https://google.com>"))


startActivity(intent)

AlertDialog (Popup Message)


AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Message")
.setPositiveButton("OK") { _, _ -> }
.show()

Menu Options (Adding Buttons in App Bar)


override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}

Popup Menu (Right-Click Style)


val popup = PopupMenu(this, view)
popup.menuInflater.inflate(R.menu.menu_main, popup.menu)
popup.show()

Context Menu (Long Press Menu)


override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo:
ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.menu_main, menu)
}

Notification
combined Page 1
Notification
val notification = NotificationCompat.Builder(this, "channel_id")
.setContentTitle("Title")
.setContentText("Message")
.setSmallIcon(R.drawable.ic_notification)
.build()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1, notification)

Progress Bar
progressBar.visibility = View.VISIBLE // Show
progressBar.visibility = View.GONE // Hide

SharedPreferences (Save & Retrieve Data)


• Save Data

val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)


prefs.edit().putString("key", "value").apply()
• Retrieve Data

val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)


val value = prefs.getString("key", "default")

Geolocation (Getting User Location)


val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
val location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)

Step 1: Activity & Intent (Move Between Screens)


Trick:
• If you move to another screen → Use Intent in MainActivity.kt
• Every screen needs an XML file → activity_main.xml, activity_second.xml
ain c vity. t
kotlin
CopyEdit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
}
econ c vity. t
kotlin
CopyEdit
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
}

combined Page 2
}
}
n roi anifest.xml ( the secon ac vity)
xml
CopyEdit
<activity android:name=".SecondActivity" />
ac vity main.xml
xml
CopyEdit
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Next Screen"/>
ac vity secon .xml
xml
CopyEdit
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Second Screen"/>

Step 2: AlertDialog (Popup Message)


Trick: Always use AlertDialog.Builder(this)
ain c vity. t
kotlin
CopyEdit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("Warning")
.setMessage("Are you sure?")
.setPositiveButton("OK") { _, _ -> }
.setNegativeButton("Cancel") { _, _ -> }
.show()
}
}
}
ac vity main.xml
xml
CopyEdit
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Alert"/>

Step 3: Options Menu (Top Right Menu)


Trick: Use onCreateOptionsMenu (to show menu) and onOptionsItemSelected (to handle click).

combined Page 3
Trick: Use onCreateOptionsMenu (to show menu) and onOptionsItemSelected (to handle click).
ain c vity. t
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.option1 -> Toast.makeText(this, "Option 1 clicked", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
men main.xml (Insi e res men fol er)
<menu xmlns:android="<http://schemas.android.com/apk/res/android>">
<item android:id="@+id/option1"
android:title="Option 1"/>
</menu>

Step 4: Popup Menu (Right-Click Style)


Trick: Use PopupMenu(this, view)
ain c vity. t
button.setOnClickListener {
val popup = PopupMenu(this, it)
popup.menuInflater.inflate(R.menu.menu_main, popup.menu)
popup.show()
}

Step 5: Context Menu (Long Press)


Trick: Use onCreateContextMenu
ain c vity. t
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo:
ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.menu_main, menu)
}

Step 6: Notification (Show in Status Bar)


Trick: Use NotificationCompat.Builder
ain c vity. t
kotlin
CopyEdit
val notification = NotificationCompat.Builder(this, "channel_id")
.setContentTitle("New Message")
.setContentText("You have a new notification")
.setSmallIcon(R.drawable.ic_notification)
.build()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1, notification)

Step 7: Progress Bar (Loading Indicator)


combined Page 4
Step 7: Progress Bar (Loading Indicator)
Trick: Show/hide using visibility
ain c vity. t
kotlin
CopyEdit
progressBar.visibility = View.VISIBLE // Show
progressBar.visibility = View.GONE // Hide
ac vity main.xml
xml
CopyEdit
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Step 8: SharedPreferences (Save & Retrieve Data)


Trick: Use getSharedPreferences("NAME", MODE_PRIVATE)
ave ata
kotlin
CopyEdit
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
prefs.edit().putString("key", "value").apply()
Retrieve ata
kotlin
CopyEdit
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val value = prefs.getString("key", "default")

Step 9: Geolocation (Get User Location)


Trick: Use getSystemService(Context.LOCATION_SERVICE)
ain c vity. t
kotlin
CopyEdit
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
val location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)

Final Tricks to Remember Everything


1. If it moves to another screen → Intent
2. If it shows a pop-up → AlertDialog
3. If it saves data → SharedPreferences
4. If it tracks location → LocationManager
5. If it shows progress → ProgressBar
6. If it adds a menu → onCreateOptionsMenu
7. If it shows a notification → NotificationCompat

Step 1: Activity & Intent (Move Between Screens)


Trick:
• Every new screen needs XML (activity_main.xml, activity_second.xml).
• If you move to another screen → Use Intent in MainActivity.kt
• Remember → Find → Click → Intent → Start (FCIS)
Syntax Breakdown:

combined Page 5
Syntax Breakdown:
kotlin
CopyEdit
val button = findViewById<Button>(R.id.button) // Find Button
button.setOnClickListener { // Set Click
val intent = Intent(this, SecondActivity::class.java) // Create Intent
startActivity(intent) // Start Activity
}
✅ Memory Trick → "Find → Click → Intent → Start (FCIS)"

Step 2: AlertDialog (Popup Message)


Trick:
• Always use → AlertDialog.Builder(this)
• Remember: Title → Message → Buttons → Show

.set itle " a nin " et itle


.setMessa e "A e yo s e " et Messa e
.set osi ve on " " _, _ ✅ osi ve on
.set e a ve on " ancel" _, _ e a ve on
.s o o
✅ Memory Trick → "Title → Message → Buttons → Show" (T-M-B-S)

Step 3: Options Menu (Top Right Menu)


Trick:
• To show menu → on eate ptionsMen
• To handle click → on ptionsItem elected
kotlin
CopyEdit
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu) // Load Menu
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) { // Handle Click
R.id.option1 -> Toast.makeText(this, "Option 1 clicked", Toast.LENGTH_SHORT).show() //
Show Toast
}
return super.onOptionsItemSelected(item)
}
✅ Memory Trick → "Show → Handle Click"

Step 4: Popup Menu (Right-Click Style)


Trick:
• Always use → PopupMenu(this, view)
kotlin
CopyEdit
button.setOnClickListener {
val popup = PopupMenu(this, it) // Create Popup
popup.menuInflater.inflate(R.menu.menu_main, popup.menu) // Load Menu
popup.show() // Show Popup
}

combined Page 6
}
✅ Memory Trick → "Create → Load → Show" (C-L-S)

Step 5: Context Menu (Long Press)


Trick:
• Always use → onCreateContextMenu
kotlin
CopyEdit
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo:
ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.menu_main, menu) // Load Context Menu
}
✅ Memory Trick → "Long Press → Load Menu"

Step 6: Notification (Show in Status Bar)


Trick:
• Always use → NotificationCompat.Builder
kotlin
CopyEdit
val notification = NotificationCompat.Builder(this, "channel_id")
.setContentTitle("New Message") // Title
.setContentText("You have a new notification") // Message
.setSmallIcon(R.drawable.ic_notification) // Icon
.build()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1, notification) // Send Notification
✅ Memory Trick → "Title → Message → Icon → Send" (T-M-I-S)

Step 7: Progress Bar (Loading Indicator)


Trick:
• Always use → progressBar.visibility
kotlin
CopyEdit
progressBar.visibility = View.VISIBLE // Show Progress
progressBar.visibility = View.GONE // Hide Progress
✅ Memory Trick → "Visible = Show, Gone = Hide"

Step 8: SharedPreferences (Save & Retrieve Data)


Trick:
• Use getSharedPreferences("NAME", MODE_PRIVATE)
kotlin
CopyEdit
// Save Data
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
prefs.edit().putString("key", "value").apply() // Save Key-Value
// Retrieve Data
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val value = prefs.getString("key", "default") // Get Data
✅ Memory Trick → "Save = putString, Retrieve = getString"

Step 9: Geolocation (Get User Location)


combined Page 7
Step 9: Geolocation (Get User Location)
Trick:
• Always use → getSystemService(Context.LOCATION_SERVICE)
import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

class MainActivity : AppCompatActivity() {


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

val tvLocation = findViewById<TextView>(R.id.tvLocation)


val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 100)
return
}

val location: Location? =


locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
tvLocation.text = location?.let {
"Lat: ${it.latitude}, Lng: ${it.longitude}"
} ?: "Location not available"
}
}

✅ Memory Trick → "System Service → Get Last Location"

Final Cheat Sheet


Feature Syntax Memory Trick
Activity Switch Intent(this, SecondActivity::class.java) Find → Click → Intent → Start (FCIS)
AlertDialog AlertDialog.Builder(this) Title → Message → Buttons → Show
(T-M-B-S)
Options Menu onCreateOptionsMenu, Show → Handle Click
onOptionsItemSelected
Popup Menu PopupMenu(this, view) Create → Load → Show (C-L-S)
Context Menu onCreateContextMenu Long Press → Load Menu
Notification NotificationCompat.Builder Title → Message → Icon → Send (T-M-
I-S)
Progress Bar progressBar.visibility = Visible = Show, Gone = Hide
View.VISIBLE/GONE
SharedPreferen getSharedPreferences("NAME", Save = putString, Retrieve = getString
ces MODE_PRIVATE)

combined Page 8
ces MODE_PRIVATE)
Geolocation getSystemService(Context.LOCATION_SE System Service → Get Last Location
RVICE)

Best Trick to Memorize Everything


If c ’ m mb c , m mb what it does, then write what makes sense!
Just remember this simple guide:
• Switch Screen? → Intent
• Popup? → Ale tDialo
• Menu? → on eate ptionsMen
• Notification? → otification ompat
• Save Data? → a ed efe ences
• Progress? → o ess a
• Location? → LocationMana e

combined Page 9
26 February 2025 21:23

Android Notifications
Introduction
A notification is a message that can be displayed to the user of our application. Notifications help users stay informed about updates, alerts, or
events happening in the background of an application.

Types of Notifications
1. Toast Notification
2. Status Notification
3. Dialog Notification

1. Toast Notification
A Toast notification is a message that appears on the screen and fades away after a few seconds. It does not require user interaction and is best
suited for displaying short messages.
Context
Context is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources, classes,
and application-level operations such as launching activities, broadcasting intents, etc.
getApplicationContext()
This method returns the context for the entire application (the process in which all activities are running).
Creating a Toast Notification
val toast = Toast.makeText(context, "Hello, World!", Toast.LENGTH_SHORT)
toast.setGravity(Gravity.CENTER, 0, 0) // Optional: Positioning the toast
toast.show()

2. Dialog Notifications
Dialogs are small windows that prompt the user to make a decision or enter additional information. They do not fill the entire screen and are
used for important user interactions.
Types of Dialogs
1. AlertDialog
2. ProgressDialog
3. DatePickerDialog / TimePickerDialog
AlertDialog
An AlertDialog is a pop-up window that displays a message and buttons for user interaction.
Creating an AlertDialog
val builder = AlertDialog.Builder(this)
val positiveButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext, "Yes", Toast.LENGTH_SHORT).show()
}
val negativeButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext, "No", Toast.LENGTH_SHORT).show()
}
builder.setTitle("Confirmation")
.setMessage("Are you sure?")
.setPositiveButton("Yes", positiveButtonClick)
.setNegativeButton("No", negativeButtonClick)
.setCancelable(true)
.show()
ProgressDialog
A progress bar is used to indicate the progress of a background task, such as downloading or uploading.
Creating a Progress Bar
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="0"
android:max="100"
style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Horizontal" />
lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

progressBar = findViewById(R.id.progressBar)
incrementProgress()
}

theory Page 10
}
private fun incrementProgress() {
Thread {
for (i in 1..100) {
Thread.sleep(50) // Simulate work
runOnUiThread {
progressBar.progress = i
}
}
}.start()
}
DatePickerDialog & TimePickerDialog
These dialogs allow users to select a date or time.
Creating a DatePickerDialog
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(this, { _, selectedYear, selectedMonth, selectedDay ->
val formattedDate = "$selectedDay/${selectedMonth + 1}/$selectedYear"
selectedDateTextView.text = formattedDate
}, year, month, day)
datePickerDialog.show()
Creating a TimePickerDialog
val calendar = Calendar.getInstance()
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val timePickerDialog = TimePickerDialog(this, { _, selectedHour, selectedMinute ->
val formattedTime = String.format("%02d:%02d", selectedHour, selectedMinute)
selectedTimeTextView.text = formattedTime
}, hour, minute, true)
timePickerDialog.show()

3. Status Notification
A status notification displays rich information from a background service and appears in the status bar.
Adding Permission
Add the following permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
Creating a Notification Channel
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Example Channel"
val descriptionText = "This is a sample notification channel"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("example_channel_id", name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Sending a Notification
private fun sendNotification() {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val builder = NotificationCompat.Builder(this, "example_channel_id")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Hello, User!")
.setContentText("This is a sample notification.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
with(NotificationManagerCompat.from(this)) {
if (ActivityCompat.checkSelfPermission(
applicationContext,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED) {
return

theory Page 11
return
}
notify(1, builder.build())
}
}
Android Menus
Menus are a common user interface component in many types of applications. They provide options for a list of actions that a user can take.
Types of Menus in Android
1. Options Menu
2. Context Menu
3. Popup Menu
Option Menu
The options menu is the primary collection of menu items for an activity. It is where actions such as "Search," "Settings," and "Logout" are
typically placed.
Steps to Create an Options Menu
1. Create a Menu Resource Directory
○ Navigate to res → e → And oid Reso ce Di ecto y → elect men as t e eso ce type.
2. Create a Menu XML File
○ Right-click on res/menu → e → Men Reso ce File → ame it men .xml.
3. Add Items in the XML File
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_share"
android:title="@string/action_share"
app:showAsAction="never" />
</menu>
Handling Menu Actions in Kotlin (MainActivity.kt)
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.action_share -> {
Toast.makeText(this, "Share Selected", Toast.LENGTH_SHORT).show()
}
R.id.action_settings -> {
Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show()
}
}
return super.onOptionsItemSelected(item)
}
Popup Menu
A Popup Menu appears below the anchor text if space is available; otherwise, it appears above the anchor text. It disappears if you click outside
the menu.
Steps to Create a Popup Menu
1. Create a Menu Resource File (popup_menu.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/java" android:title="Java" />
<item android:id="@+id/kotlin" android:title="Kotlin" />
<item android:id="@+id/android" android:title="Android" />
</menu>
1. Create a Button in activity_main.xml
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu" />
1. Implement the Popup Menu in MainActivity.kt
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val popupMenu = PopupMenu(this, button)
popupMenu.menuInflater.inflate(R.menu.popup_menu, popupMenu.menu)
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.java -> Toast.makeText(this, "Java Selected", Toast.LENGTH_SHORT).show()
R.id.kotlin -> Toast.makeText(this, "Kotlin Selected", Toast.LENGTH_SHORT).show()
}
true
}

theory Page 12
}
popupMenu.show()
}
Context Menu
A Context Menu is a floating list of menu items that appears when a user long-presses a view. It provides contextual actions related to the
selected item.
Steps to Create a Context Menu
1. Register the View for Context Menu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerForContextMenu(findViewById(R.id.textView))
}
1. Define the Context Menu in onCreateContextMenu
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menu.setHeaderTitle("Choose an Option")
menu.add(0, v.id, 0, "Copy")
menu.add(0, v.id, 0, "Delete")
}
1. Handle Context Menu Selection
override fun onContextItemSelected(item: MenuItem): Boolean {
return when (item.title) {
"Copy" -> {
Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show()
true
}
"Delete" -> {
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show()
true
}
else -> super.onContextItemSelected(item)
}
}
Summary of Menus in Android
Menu Type Description
Options Menu Global menu for the activity, placed in the app bar.
Popup Menu Temporary menu appearing next to an anchor view.
Context Menu Menu that appears on long-press for contextual actions.
This document provides a detailed explanation of Android menus, their types, and how to implement them. Let me know if you need any
modifications or additional explanations!

From <https://chatgpt.com/c/67bef026-5964-800a-99d5-9be4cef8b588>

1. Android Layouts
Android layouts define how UI components (views and widgets) are arranged in an activity or fragment.

1.1 LinearLayout
• Arranges children vertically (default) or horizontally.
• Uses android:orientation="vertical" or "horizontal".
Example
xml
CopyEdit
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>

theory Page 13
1.2 RelativeLayout
• Positions children relative to each other or the parent.
• Uses attributes like layout_above, layout_below, layout_alignParentTop, etc.
Example
xml
CopyEdit
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:layout_below="@id/btn1" />
</RelativeLayout>

1.3 ConstraintLayout (Recommended)


• The most flexible layout, allowing complex positioning.
• Uses constraints to define positions.
Example
xml
CopyEdit
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

1.4 FrameLayout
• Used for stacking views on top of each other.
• Commonly used for fragments.
Example
xml
CopyEdit
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/sample_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overlay Text"
android:layout_gravity="center"/>
</FrameLayout>

2. Android Views & Widgets


Views are UI components like TextView, Button, EditText, etc.

theory Page 14
Views are UI components like TextView, Button, EditText, etc.

2.1 TextView
• Displays text.
Example
xml
CopyEdit
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:textSize="20sp"
android:textColor="#FF0000"/>

2.2 EditText
• Allows users to input text.
Example
xml
CopyEdit
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"/>

2.3 Button
• Triggers actions when clicked.
Example
xml
CopyEdit
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="buttonClicked"/>
In Activity (Kotlin)

kotlin
CopyEdit
fun buttonClicked(view: View) {
Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show()
}

2.4 ImageView
• Displays images.
Example
xml
CopyEdit
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sample_image"/>

2.5 CheckBox
• Allows multiple selections.
Example
xml
CopyEdit
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accept Terms & Conditions"/>

theory Page 15
2.6 RadioButton
• Used in RadioGroup for single selection.
Example
xml
CopyEdit
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"/>
</RadioGroup>

2.7 Switch
• Used for on/off toggling.
Example
xml
CopyEdit
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable Notifications"/>

2.8 ProgressBar
• Displays a loading animation.
Example
xml
CopyEdit
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

2.9 SeekBar
• Allows users to adjust values (e.g., volume control).
Example
xml
CopyEdit
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

2.10 RecyclerView (Recommended for Lists)


• Efficient list handling (better than ListView).
• Requires Adapter & ViewHolder.
Example
1. Add Dependency

gradle
CopyEdit
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.2.1'
}
2. RecyclerView Layout

xml
CopyEdit

theory Page 16
CopyEdit
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3. Item Layout (item_row.xml)

xml
CopyEdit
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item Name"/>
4. Adapter (Kotlin)

kotlin
CopyEdit
class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.findViewById<TextView>(R.id.textView).text = items[position]
}
override fun getItemCount() = items.size
}
5. Set RecyclerView in Activity

kotlin
CopyEdit
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = MyAdapter(listOf("Item 1", "Item 2", "Item 3"))

Conclusion
• Use ConstraintLayout for modern apps.
• Prefer RecyclerView over ListView.
• Follow Material Design Guidelines.
• Test UI with different screen sizes.

1. Activity Class :
• The Activity class is a crucial component of Android applications.
• Every app has at least one Activity, which acts as the entry point for interacting with users.
• Unlike traditional programming languages where main() is the entry point, Android initiates code execution in an Activity instance through
specific lifecycle callback methods.
2. Activity Lifecycle Methods :
• onCreate() :
• Called when the activity is first created.
• Used to initialize essential components of the activity.
• Takes a Bundle object parameter (savedInstanceState) which contains the previous state data if the activity is being re-initialized.

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
• onPause() :
• Called when the activity is no longer in the foreground but is still visible.
• Example scenario: When another activity is launched in front of the current one.

override fun onPause() {


super.onPause()
}
3. Setting Layout :
• Use setContentView() to set the layout for an activity.
• This function takes a view parameter, typically pointing to an XML layout file.

setContentView(R.layout.activity_main)
4. Declaring Activities in Manifest :
• Every activity must be declared in the AndroidManifest.xml file within the <application> tag.
• The main activity should have an <intent-filter> with MAIN action and LAUNCHER category.

theory Page 17
<activity android:name=".SecondActivity"></activity>
5. Permissions :
• Any service or feature (like Internet, Bluetooth) requires permissions declared in the manifest.

<uses-permission android:name="android.permission.INTERNET"/>
6. AppCompatActivity :
• Extends the Activity class and provides compatibility with older versions of Android.

class MainActivity : AppCompatActivity() {


// Activity code
}
AndroidManifest.xml
7. Overview :
• Every Android project includes a AndroidManifest.xml file located in the root directory.
• This file defines the structure, metadata, components, and requirements of the application.
8. Main Components :
• manifest : The root element specifying the package name.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
</manifest>
9. uses-sdk : Specifies the minimum, maximum, and target SDK versions.
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="30" />
10. uses-permission : Declares permissions required by the app.
<uses-permission android:name="android.permission.INTERNET" />
11. application : Contains metadata and acts as a container for components.
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
</application>
12. activity : Defines activities within the app.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
13. intent-filter : Specifies the types of intents the component can respond to.
xml

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
14. uses-feature : Specifies hardware features required by the app.
<uses-feature android:name="android.hardware.camera" />
15. permission : Defines custom permissions.
<permission android:name="com.example.myapp.permission.ACCESS_DATA" />
16. Attributes :
• versionCode & versionName : Define the app's version.
android:versionCode="1"
android:versionName="1.0"
17. installLocation : Specifies whether the app should be installed on internal storage or SD card.
android:installLocation="auto"
18. Additional Elements :
• uses-library : Links against shared libraries.
<uses-library android:name="com.google.android.maps" />
• uses-configuration : Specifies input mechanisms supported by the app.
xml
Copy
1

<uses-configuration android:reqFiveWayNav="true" />


Sample Kotlin Code for Basic Activity Declaration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Sample AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="30" />

theory Page 18
android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" />
</application>
</manifest>
Summary
• Understand the structure and importance of the AndroidManifest.xml file.
• Declare all necessary components (activities, services, etc.) within the manifest.
• Use attributes like versionCode, versionName, and installLocation appropriately.
• Specify required permissions and features to ensure proper functionality.
• Utilize intent filters to define how components interact with intents.

Services in Android
19. What is a Service?
• A Service is an Android component that allows an application to perform long-running operations in the background without a user interface.
• It ensures that tasks continue running even if the user switches to another app or the app's UI is destroyed.
20. Types of Android Services
• Foreground Services :
• Notify the user about ongoing operations (e.g., downloading files).
• Example: Music player showing a notification while playing music.
• Background Services :
• Perform tasks without notifying the user.
• Example: Syncing data in the background.
• Bound Services :
• Allow components (like Activities) to bind to the service for inter-process communication (IPC).
• Example: A chat app binding to a messaging service.
21. Lifecycle of Android Services
• Started Service (Unbounded) :
• Starts with startService() and runs indefinitely until stopped using stopService() or stopSelf().
• Bound Service :
• Starts when a component binds to it using bindService() and stops when all components unbind using unbindService().
22. Important Callback Methods
• onStartCommand() :
• Called when a component starts the service using startService().
• Returns an integer indicating how the system should handle the service if it gets terminated.
• onBind() :
• Mandatory to implement; called when a component binds to the service using bindService().
• Returns an IBinder object for communication with the service.
• onUnbind() :
• Called when all clients disconnect from the service.
• onRebind() :
• Called when new clients connect after all previous clients disconnected.
• onCreate() :
• Called when the service is first created.
• onDestroy() :
• Called when the service is no longer in use and is being destroyed.
23. Declaring Services in the Manifest
• Every service must be declared in the AndroidManifest.xml file within the <application> tag.
xml
Copy
1

<service android:name=".NewService" />


24. Use Cases
• Playing music in the background.
• Downloading files.
• Syncing data with a server.
• Performing periodic tasks.

Why is Gradle Needed?

Every Android project needs a Gradle for generating an apk from the .java and .xml files in the project.
Simply put, a Gradle takes all the source files (java and XML) and applies appropriate tools, e.g., converts
the java files into dex files and compresses all of them into a single file known as apk that is actually used.

theory Page 19
the java files into dex files and compresses all of them into a single file known as apk that is actually used.
There are two types of build.gradle scripts
• Top-level build.gradle
• Module-level build.gradle

CardView is a new widget in Android that can be used to display any sort of data by providing a rounded
corner layout along with a specific elevation. CardView is the view that can display views on top of each
other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget
can be easily seen in many different Android Apps. CardView can be used for creating items in listview or
inside RecyclerView. The best part about CardView is that it extends Framelayout and it can be displayed on
all platforms of Android. Now we will see the simple example of CardView implementation.

theory Page 20
26 February 2025 22:33

Function to Open Another Activity


fun openSecondActivity() {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
Usage
button.setOnClickListener {
openSecondActivity()
}

Open a Webpage
fun openWebsite(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
Usage
button.setOnClickListener {
openWebsite("https://www.google.com")
}

intents Page 21
menu
26 February 2025 23:00

3 Types of Menus in Android (with Full Code)


Below are full working examples for:
Op ons en m
Context en m
op p en c c m

Op ons en ( op Right en )
Concept: Appears at the top-right of the app when clicking the three-dot menu.
Steps to Implement:
men main.xml m
m
I m c c c
menu_main.xml (res/menu/menu_main.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/option1"
android:title="Option 1"/>
<item
android:id="@+id/option2"
android:title="Option 2"/>
</menu>
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu) // Inflate menu
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.option1 -> Toast.makeText(this, "Option 1 clicked", Toast.LENGTH_SHORT).show()
R.id.option2 -> Toast.makeText(this, "Option 2 clicked", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
}
Trick to Remember:
M.O.I. → Menu XML, OnCreateOptionsMenu, Item Click

Context en (Long ress en )


Concept: Appears when the user long-presses a UI element.
Steps to Implement:
f c m
m
I m c m c c
menu_context.xml (res/menu/menu_context.xml)
menu Page 22
menu_context.xml (res/menu/menu_context.xml)
xml
CopyEdit
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/delete"
android:title="Delete"/>
<item android:id="@+id/share"
android:title="Share"/>
</menu>
MainActivity.kt
kotlin
CopyEdit
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView)
registerForContextMenu(textView) // Register TextView for Context Menu
}
override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo:
ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.menu_context, menu) // Inflate Context Menu
}
override fun onContextItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.delete -> Toast.makeText(this, "Delete clicked", Toast.LENGTH_SHORT).show()
R.id.share -> Toast.makeText(this, "Share clicked", Toast.LENGTH_SHORT).show()
}
return super.onContextItemSelected(item)
}
}
Trick to Remember:
C.R.I. → Context menu XML, Register view, Item Click

op p en ( on Clic en )
Concept: Appears near a button when clicked.
Steps to Implement:
c m m
m
c
menu_popup.xml (res/menu/menu_popup.xml)
xml
CopyEdit
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/edit"
android:title="Edit"/>
<item android:id="@+id/save"
android:title="Save"/>
</menu>

menu Page 23
</menu>
activity_main.xml
xml
CopyEdit
<Button
android:id="@+id/btnPopup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup"
android:layout_centerInParent="true"/>
MainActivity.kt
kotlin
CopyEdit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnPopup = findViewById<Button>(R.id.btnPopup)
btnPopup.setOnClickListener {
val popup = PopupMenu(this, btnPopup)
popup.menuInflater.inflate(R.menu.menu_popup, popup.menu)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.edit -> Toast.makeText(this, "Edit clicked", Toast.LENGTH_SHORT).show()
R.id.save -> Toast.makeText(this, "Save clicked", Toast.LENGTH_SHORT).show()
}
true
}
popup.show()
}
}
}
Trick to Remember:
B.P.I. → Button Click, Popup Menu XML, Item Click

Summary of 3 Menus
Menu Triggered By Steps to Implement Best Used For
Type
Options Clicking the top- onCreateOptionsMenu(), App-wide actions like
Menu right menu onOptionsItemSelected() settings, logout
Context Long-pressing a registerForContextMenu(), Actions related to a
Menu view (e.g., onCreateContextMenu(), specific item (e.g., delete,
TextView) onContextItemSelected() share)
Popup Clicking a button PopupMenu, Temporary actions related
Menu setOnMenuItemClickListener() to a button

menu Page 24
Geolocation ,notifications,shared pref
26 February 2025 23:32

Geocoder in Android
1. What is Geocoder?
○ Converts latitude & longitude into a human-readable address.
○ Requires internet access and location permissions.
2. Permissions Needed in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
3. Simple XML Layout (activity_main.xml)

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetching address..."
android:textSize="18sp"
android:padding="16dp"/>

Simplified Code: MainActivity.kt


import android.location.Geocoder
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView: TextView = findViewById(R.id.textView)
val latitude = 9.9129
val longitude = 78.1477
textView.text = getAddress(latitude, longitude) ?: "Address not found"
}
private fun getAddress(lat: Double, lng: Double): String? {
return try {
val geocoder = Geocoder(this, Locale.getDefault())
val addressList = geocoder.getFromLocation(lat, lng, 1)
addressList?.firstOrNull()?.getAddressLine(0) ?: "No address found"
} catch (e: Exception) {
e.printStackTrace()
"Error fetching address"
}
}
}

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

Geolocation ^Jnotifications^Jshared pref Page 25


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

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

private fun requestNotificationPermission() {


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS), 101)
}
}
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,


grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)

if (requestCode == 101) {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Notification Permission Granted!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Permission Denied! No notifications for you.",
Toast.LENGTH_SHORT).show()
}
}
}
}

Shared preference
<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">

<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Name" />

<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Geolocation ^Jnotifications^Jshared pref Page 26


android:layout_height="wrap_content"
android:text="Save Name" />

<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saved Name will appear here" />
</LinearLayout>

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

class MainActivity : AppCompatActivity() {


lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val etName = findViewById<EditText>(R.id.etName)


val btnSave = findViewById<Button>(R.id.btnSave)
val tvResult = findViewById<TextView>(R.id.tvResult)

// Initialize Shared Preferences


sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)

// Retrieve saved name on app start


val savedName = sharedPreferences.getString("name", "No Name Saved")
tvResult.text = "Saved Name: $savedName"

// Save name on button click


btnSave.setOnClickListener {
val name = etName.text.toString()
sharedPreferences.edit().putString("name", name).apply()
tvResult.text = "Saved Name: $name"
}
}
}

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

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices

Geolocation ^Jnotifications^Jshared pref Page 27


import com.google.android.gms.location.LocationServices

class MainActivity : AppCompatActivity() {


private lateinit var fusedLocationClient: FusedLocationProviderClient

private val locationPermissionRequest =


registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
getLocation(findViewById(R.id.tvLocation))
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show()
}
}

override fun onCreate(savedInstanceState: Bundle?) {


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

val tvLocation = findViewById<TextView>(R.id.tvLocation)


fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

// Request permission dynamically


if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
locationPermissionRequest.launch(Manifest.permission.ACCESS_FINE_LOCATION)
} else {
getLocation(tvLocation)
}
}

private fun getLocation(tvLocation: TextView) {


fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
if (location != null) {
tvLocation.text = "Lat: ${location.latitude}, Lng: ${location.longitude}"
} else {
tvLocation.text = "Location not found"
}
}
}
}

Geolocation ^Jnotifications^Jshared pref Page 28

You might also like