0% found this document useful (0 votes)
11 views15 pages

501 02 CH 5

The document provides a comprehensive guide on setting up a virtual server using XAMPP for Android application development, including steps for installing and accessing the server. It also covers connecting an Android app to a database for CRUD operations and accessing the user's location using Kotlin, along with handling permissions. Additionally, it includes instructions for capturing images using the device camera through an Intent, with detailed code examples for implementation.

Uploaded by

cd217251
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)
11 views15 pages

501 02 CH 5

The document provides a comprehensive guide on setting up a virtual server using XAMPP for Android application development, including steps for installing and accessing the server. It also covers connecting an Android app to a database for CRUD operations and accessing the user's location using Kotlin, along with handling permissions. Additionally, it includes instructions for capturing images using the device camera through an Intent, with detailed code examples for implementation.

Uploaded by

cd217251
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/ 15

A.Y.

- 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing
Unit-5: Storing Android application data using Database and JSON [Any
open-source database can be used. MySQL or SQLite is preferable]

5.1 Setting up virtual server on local computer


Setting up a virtual server on your local computer allows you to simulate a real server
environment for testing and development purposes. Here’s a step-by-step guide on how to
set up a virtual server on your local machine using a popular tool like XAMPP (for PHP,
MySQL, and Apache)

Option 1: Setting Up a Local Web Server Using XAMPP


XAMPP is a free and open-source cross-platform web server solution stack package, which
includes Apache, MariaDB (MySQL), and PHP. It is easy to install and use, making it ideal
for setting up a local server environment.

Step 1: Download and Install XAMPP


1. Download XAMPP:
o Go to the official XAMPP website: https://www.apachefriends.org/index.html.
o Download the XAMPP installer for your operating system (Windows, macOS,
or Linux).
2. Install XAMPP:
o Run the installer and follow the installation instructions.
o Choose the components you want to install. By default, Apache, MySQL, and
PHP will be selected. You can leave other components selected or deselect
them as needed.
o Choose the installation directory (default is C:\xampp on Windows).

Step 2: Start the XAMPP Control Panel


1. Open XAMPP:
o After installation, open the XAMPP Control Panel.
o You can find it in the installation directory or search for "XAMPP Control Panel"
in your operating system.
2. Start Apache and MySQL:
o In the XAMPP Control Panel, click the "Start" button next to Apache and
MySQL.
o Both services should turn green, indicating they are running.

Step 3: Access Your Local Server


1. Open a Web Browser:
o Open your web browser and enter http://localhost or http://127.0.0.1 in the
address bar.
o You should see the XAMPP welcome page, indicating that your local server is
set up and running.
2. Place Your Files:
o Place your PHP or HTML files in the htdocs folder within the XAMPP installation
directory (e.g., C:\xampp\htdocs).
o Access your files by entering http://localhost/yourfile.php in the browser.
Prof. Bhumika Patel Page 1

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing
5.2 Connecting Android based App with Database 5.3 CRUD
operations (Create, Read, Update, Delete) using APP: 5.3.1
Create and insert data to the database
5.3.2 Read, Update and Delete data from database.
Prof. Bhumika Patel Page 2

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing

5.4 Accessing user’s current location


To access the user's current location and determine the country name in an Android
application using Kotlin, you can use the FusedLocationProviderClient for getting the
location and Geocoder for converting the location into a human-readable address,
including the country name.
Step-by-Step Guide

The code sets up an Android app that uses GPS to get the user's current location
and display it in a TextView. It requests the necessary permissions dynamically and
handles location updates via the LocationManager. The app ensures that location
permissions are properly checked and requested from the user before accessing
location services.

Package Package Declaration: Specifies the package name of the app.

∙ Imports: These bring in classes required for permissions, location services,


UI components, and other necessary Android functionality. Key imports
include:
∙ ACCESS_FINE_LOCATION: Represents the permission needed to access the
device’s precise location.
∙ LocationManager and LocationListener: Used for requesting and receiving
location updates.
∙ ContextCompat and ActivityCompat: Used for checking and requesting
permissions.
∙ AppCompatActivity: The base class for activities in Android apps. Declaration
and Imports
Class Definition
∙ MainActivity extends AppCompatActivity to create an activity, which is a
single, focused thing that the user can do.
∙ Implements LocationListener to receive location updates.

Variable Declarations

locationManager: A LocationManager object used to access location

services. tvGpsLocation: A TextView where the GPS location data will be

displayed.

locationPermissionCode: An integer constant used to identify the permission


request result.

onCreate Method
override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

Prof. Bhumika Patel Page 3

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing
setContentView(R.layout.activity_main)

title = "Location App"

tvGpsLocation = findViewById(R.id.textView)

val button: Button = findViewById(R.id.getLocation)

button.setOnClickListener {

locationManager = getSystemService(LOCATION_SERVICE) as LocationManager

// Check if location permission is granted

if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

// Request location permission if not granted

ActivityCompat.requestPermissions(this, arrayOf(ACCESS_FINE_LOCATION),
locationPermissionCode)

} else {

// Request location updates if permission is already granted

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this)

∙ Purpose: Initializes the activity and sets up the layout.


∙ setContentView: Sets the UI layout for the activity.
∙ findViewById: Finds the UI components (TextView and Button) defined in the XML
layout.
∙ button.setOnClickListener: Sets a click listener on the button to start the location
update process.
∙ locationManager = getSystemService(LOCATION_SERVICE): Initializes the
LocationManager to access location services.
∙ ContextCompat.checkSelfPermission: Checks if the location permission
(ACCESS_FINE_LOCATION) is granted.
∙ If not granted, it requests the permission using ActivityCompat.requestPermissions. ∙ If
granted, it requests location updates every 5000 milliseconds (5 seconds) and with a
minimum distance change of 5 meters.

Prof. Bhumika Patel Page 4


A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -
Advanced Mobile Computing
onLocationChanged Method

Purpose: Called when the location changes.


location: Location: Receives the updated location object containing latitude and longitude.
tvGpsLocation.text: Updates the TextView to display the new location coordinates.
onRequestPermissionsResult Method
override fun onRequestPermissionsResult(requestCode: Int, permissions:
Array<out String>, grantResults: IntArray) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults)

if (requestCode == locationPermissionCode) {

if (grantResults.isNotEmpty() && grantResults[0] ==


PackageManager.PERMISSION_GRANTED) {

Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show() //

Request location updates now that permission is granted

if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
5f, this)

else

Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show() }

⮚ Purpose: Handles the result of the location permission request.


⮚ requestCode: Identifies which permission was requested (matched against
locationPermissionCode).
⮚ grantResults: Contains the result of the permission request.
⮚ If permission is granted, a toast message is shown, and location updates are requested
again.
⮚ If denied, a toast message indicates the denial.
Prof. Bhumika Patel Page 5

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing
Example:

MainActivity.java
package com.example.gmapcurrentlock

import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity(), LocationListener


{ // Implement LocationListener here
private lateinit var locationManager: LocationManager
private lateinit var tvGpsLocation: TextView
private val locationPermissionCode = 2

override fun onCreate(savedInstanceState: Bundle?)


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

title = "Location App"


tvGpsLocation = findViewById(R.id.textView)

val button: Button = findViewById(R.id.getLocation)


button.setOnClickListener {
locationManager = getSystemService(LOCATION_SERVICE) as LocationManager

// Check if location permission is granted


if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Request location permission if not granted
ActivityCompat.requestPermissions(this, arrayOf(ACCESS_FINE_LOCATION),
locationPermissionCode)
} else {
// Request location updates if permission is already granted
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this) }
}
}

// Override the onLocationChanged method of LocationListener


override fun onLocationChanged(location: Location)
{
tvGpsLocation.text = "Latitude: ${location.latitude}, Longitude: ${location.longitude}"
}

// Handle the permission request result


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

Prof. Bhumika Patel Page 6

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults) if
(requestCode == locationPermissionCode)
{
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show() //
Request location updates now that permission is granted
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this)
}
}
else
{
Toast.makeText(this, "Permission Denied", 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">

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


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!--
Required only when requesting background location access on Android 10 (API level 29) -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<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.GmapCurrentLocK"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Prof. Bhumika Patel Page 7


A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -
Advanced Mobile Computing
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="@string/hello_world"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/get_gps_location"
android:textColor="@android:color/holo_red_dark"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/getLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_centerInParent="true"
android:layout_marginTop="40dp"
android:text="@string/get_location" />

</RelativeLayout>

OUTPUT:
Prof. Bhumika Patel Page 8

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing

5.5 Capturing image using device camera (ACTION_IMAGE_CAPTURE


Intent of MediaStore class.)

An android application has been developed Capturing image using device camera. The
opening of the Camera from inside our app is achieved with the help of the
ACTION_IMAGE_CAPTURE Intent of MediaStore class.

This image shows the Image clicked by the camera and set in Imageview. When the app is
opened, it displays the “Camera” Button to open the camera. When pressed,
ACTION_IMAGE_CAPTURE Intent gets started by the MediaStore class. When the image is
captured, it is displayed in the image view.

Step-by-Step Implementation
Step 1: Create a New Project in Android Studio
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the
code for the activity_main.xml file. Comments are added inside the code to understand the
code in more detail.
∙ A Button to open the Camera
∙ An ImageView to display the captured image
Also, Assign the ID to each component along with other attributes as shown in the image
and the code below.

Also, Assign the ID to each component along with other attributes as shown in the image
and the code below.

Syntax:
android:id="@+id/id_name"

Prof. Bhumika Patel Page 9

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing

Here the given IDs are as follows:


∙ Camera Button: camera_button
∙ ImageView: click_image
<?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">

<!-- add Camera Button to open the Camera -->


<Button
android:id="@+id/camera_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:text="Camera" />

<!-- add ImageView to display the captured image -->


<ImageView
android:id="@+id/click_image"
android:layout_width="350dp"
android:layout_height="450dp"
android:layout_marginStart="30dp"
android:layout_marginTop="70dp"
android:layout_marginBottom="10dp" />
</RelativeLayout>

Working with the MainActivity File


Go to the MainActivity File and refer to the following code. Below is the code for the
MainActivity File. Comments are added inside the code to understand the code in more
detail. We will instantiate the components made in the XML file (Camera Button, ImageView)
using the findViewById() method. This method binds the created object to the UI
Components with the help of the assigned ID.
General Syntax:
val obj = findViewById<ComponentType>(R.id.IdOfTheComponent)
The Syntax for Components Used:
val cameraOpenId: Button = findViewById(R.id.camera_button)
val clickImageId: ImageView = findViewById(R.id.click_image)

Setting up Operations on the Camera Button and ImageView.


First, define the variable pic_id which is the request-id of the clicked image.
This is done as follows:

private const val picId = 123

Prof. Bhumika Patel Page 10

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing

Add the listener to the Camera button. This will be used to open the camera when the user
clicks on the button.This is done as follows:

camera_open_id.setOnClickListener {
// Your code here
}

Now create the ACTION_IMAGE_CAPTURE Intent provided by MediaStore. This Intent will
help to open the camera for capturing the image. Start the intent with the requested pic_id.
This is done as follows:

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)


startActivityForResult(cameraIntent, picId)

Now use the onActivityResult() method to get the result, here is the captured image.
This is done as follows:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { }

Then set the image received as a result of Camera intent in the ImageView for display.
val photo: Bitmap = data.extras["data"] as Bitmap
clickedimageid.setImageBitmap(photo)

Example:
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var cameraOpenId: Button


lateinit var clickImageId: ImageView

override fun onCreate(savedInstanceState: Bundle?) {


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

cameraOpenId = findViewById(R.id.camera_button)
clickImageId = findViewById(R.id.click_image)

cameraOpenId.setOnClickListener(View.OnClickListener { v: View? ->


val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, pic_id)
})

Prof. Bhumika Patel Page 11

A.Y. - 2024-25 TYBCA – SEM5 - 501-02 -


Advanced Mobile Computing
}

// This method will help to retrieve the image


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == pic_id) {
val photo = data!!.extras!!["data"] as Bitmap?
clickImageId.setImageBitmap(photo)
}
}

companion object {
private const val pic_id = 123
}
}

OUTPUT:
Source:
⮚ https://techpassmaster.com/get-current-location-in-android-studio-using-kotlin/ ⮚
https://www.geeksforgeeks.org/how-to-open-camera-through-intent-and-display-captured-image
in-android/
⮚ https://www.geeksforgeeks.org/how-to-get-current-location-in-android/
⮚ https://www.geeksforgeeks.org/using-fused-location-api-to-fetch-current-location-in
android/?ref=asr1

Prof. Bhumika Patel Page 12

You might also like