0% found this document useful (0 votes)
24 views67 pages

Practical Exam of MAD

The document provides code implementations for various Android layout types including LinearLayout, AbsoluteLayout, FrameLayout, TableLayout, and RelativeLayout, along with their respective XML and Java files. It also outlines the Android architecture, detailing the Application layer and the Linux Kernel. The document includes sample code for creating user interfaces with different layouts and a brief explanation of Android's architecture layers.
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)
24 views67 pages

Practical Exam of MAD

The document provides code implementations for various Android layout types including LinearLayout, AbsoluteLayout, FrameLayout, TableLayout, and RelativeLayout, along with their respective XML and Java files. It also outlines the Android architecture, detailing the Application layer and the Linux Kernel. The document includes sample code for creating user interfaces with different layouts and a brief explanation of Android's architecture layers.
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/ 67

Q1.

a) Develop a program to implement LinearLayout and AbsoluteLayout

LinearLayout:

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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ECDCC9"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:textColor="#6F686D"
android:text="Name: Jovita Manoj Reejhsinghani"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6F686D"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:text="Age: 18"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6F686D"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:text="Mobile Number: 9766697331"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6F686D"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:text="Program by Jovita Reejhsinghani, Roll No 10"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>

MainActivity.java

package com.vesp.exp5_1;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}
}

AbsoluteLayout:

activity_main.xml

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


<AbsoluteLayout 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"
android:layout_gravity="center"
android:background="#ECDCC9"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="100dp"
android:layout_marginBottom="10dp"
android:layout_x="107dp"
android:layout_y="259dp"
android:text="Name: Jovita Manoj Reejhsinghani"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:layout_x="170dp"
android:layout_y="298dp"
android:text="Age: 18"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:layout_x="113dp"
android:layout_y="336dp"
android:text="Mobile Number: 9766697331"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:layout_x="69dp"
android:layout_y="393dp"
android:text="Program by Jovita Reejhsinghani, Roll No 10"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</AbsoluteLayout>
MainActivity.java

package com.vesp.exp5_2;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}
}


b) List and explain any two layers of Android architecture
Android operating system is a stack of software components which is roughly divided into
five sections and four main layers as covered in the diagram above.
It includes operating systems, middleware and important applications.
Each layer in the architecture provides different services.
1. Application
2. Application Framework
3. Libraries
4. Android Runtime.
5. Linux Kernel.

1. Application:
​ All applications in the application layer are written in Java Language. The various core
applications that an android device provides include
●​ Maps
●​ Browser
●​ Contacts

3.Linux Kernel:

At the bottom of the layers is the Linux Kernel. This provides a level of abstraction between the
device hardware and it contains all the essential hardware drivers like camera, keypad, display
etc. Also, the kernel handles all the things such as networking and a vast array of device drivers.
Following are the drivers: Display, Camera, Bluetooth, Flash Memory Driver, USB, WiFi,
Keypad driver, Audio Driver, Power Management Driver.

Q2.
a) Develop a program to implement FrameLayout, TableLayout, and RelativeLayout

FrameLayout:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="@+id/main"
android:layout_height="match_parent"
android:background="#F4CAE0"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:text="Boolean"
android:textSize="20dp"
android:textColor="#291720"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:text="Integer"
android:textColor="#291720"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:textColor="#291720"
android:text="Character"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:textColor="#291720"
android:text="Long"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#291720"
android:text="Double"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|right"
android:textColor="#291720"
android:text="Float"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:text="Short Integer"
android:textColor="#291720"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="Long Integer"
android:textColor="#291720"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:textColor="#291720"
android:text="Byte"
android:textSize="20dp"
/>
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#291720"
android:layout_marginTop="70dp"
android:text="Program By Jovita Reejhsinghani, Roll No. 10”
android:textSize="20dp"
/>
</FrameLayout>

MainActivity.java
package com.vesp.exp6_2;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}
}

TableLayout:

activity_main.xml

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


<TableLayout 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"
android:layout_marginTop="225dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="@+id/main">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#eadaa2">
<TextView
android:id="@+id/text1"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="Name "
android:textSize="30dp"
android:layout_column="1"
/>
<TextView
android:id="@+id/text2"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:text="Age"
android:textSize="30dp"
android:layout_column="2"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FAF8D4">
<TextView
android:id="@+id/text3"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="Jovita "
android:textSize="20dp"
android:layout_column="1"
/>
<TextView
android:id="@+id/text4"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:text="18"
android:textSize="20dp"
android:layout_column="2"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FAF8D4">
<TextView
android:id="@+id/text5"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="Aastha "
android:textSize="20dp"
android:layout_column="1"
/>
<TextView
android:id="@+id/text6"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:text="19"
android:textSize="20dp"
android:layout_column="2"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FAF8D4">
<TextView
android:id="@+id/text7"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="Muskan "
android:textSize="20dp"
android:layout_column="1"
/>
<TextView
android:id="@+id/text8"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:text="18"
android:textSize="20dp"
android:layout_column="2"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FAF8D4">
<TextView
android:id="@+id/text11"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="Gaurav "
android:textSize="20dp"
android:layout_column="1"
/>
<TextView
android:id="@+id/text12"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:text="19"
android:textSize="20dp"
android:layout_column="2"
/>
</TableRow>
</TableLayout>

MainActivity.java
package com.vesp.exp6_1;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}

RelativeLayout:

activity_main.xml

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="20dp">

<TextView

android:id="@+id/label"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Username:"
android:textSize="18sp" />

<EditText

android:id="@+id/username"

android:layout_width="200dp"

android:layout_height="wrap_content"

android:layout_toEndOf="@id/label"

android:layout_marginStart="10dp"

android:hint="Enter name" />

<Button

android:id="@+id/loginBtn"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Login"

android:layout_below="@id/username"

android:layout_alignStart="@id/username"

android:layout_marginTop="20dp" />

</RelativeLayout>

MainActivity.java

package com.example.relativelayoutdemo;

import android.os.Bundle;
import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText username;

Button loginBtn;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

username = findViewById(R.id.username);

loginBtn = findViewById(R.id.loginBtn);

loginBtn.setOnClickListener(v -> {

String name = username.getText().toString();

Toast.makeText(this, "Welcome " + name, Toast.LENGTH_SHORT).show();

});

}

b) What is OHA and list its members

OHA was formed in Nov 2007.The OHA has approximately 80 member companies, including HTC,
Dell, Intel, Motorola, Qualcomm and Google. The OHA's main product is the Android platform - the
world's most popular smartphone platform.

Q3.

a) Develop a program to implement Student Registration Form

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/nameEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Name"
android:layout_marginTop="50dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<EditText
android:id="@+id/ageEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Age"
android:layout_marginTop="20dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toBottomOf="@id/nameEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<EditText
android:id="@+id/phoneEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:layout_marginTop="20dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toBottomOf="@id/ageEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<EditText
android:id="@+id/addressEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Address"
android:layout_marginTop="20dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toBottomOf="@id/phoneEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<Button
android:id="@+id/submitButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="18sp"
app:layout_constraintTop_toBottomOf="@id/addressEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="30dp" />

<TextView
android:id="@+id/nameAgeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name and Age will be displayed here"
android:textSize="16sp"
android:layout_marginTop="20dp"
app:layout_constraintTop_toBottomOf="@id/submitButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<TextView
android:id="@+id/phoneAddressTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone and Address will be displayed here"
android:textSize="16sp"
android:layout_marginTop="10dp"
app:layout_constraintTop_toBottomOf="@id/nameAgeTextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.vesp.exp7_2;

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

public class MainActivity extends AppCompatActivity {


EditText nameEditText, ageEditText, phoneEditText, addressEditText;
Button submitButton;
TextView nameAgeTextView, phoneAddressTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditText);
ageEditText = findViewById(R.id.ageEditText);
phoneEditText = findViewById(R.id.phoneEditText);
addressEditText = findViewById(R.id.addressEditText);
submitButton = findViewById(R.id.submitButton);
nameAgeTextView = findViewById(R.id.nameAgeTextView);
phoneAddressTextView = findViewById(R.id.phoneAddressTextView);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameEditText.getText().toString();
String age = ageEditText.getText().toString();
String phone = phoneEditText.getText().toString();
String address = addressEditText.getText().toString();

if (!name.isEmpty() && !age.isEmpty() && !phone.isEmpty() &&


!address.isEmpty()) {
nameAgeTextView.setText("Name: " + name + ", Age: " + age);
phoneAddressTextView.setText("Phone: " + phone + ", Address: " +
address);
} else {
Toast.makeText(MainActivity.this, "Please fill in all fields",
Toast.LENGTH_SHORT).show();
}
}
});
}
}


b) What is the need of Android?

Android is an open-source mobile operating system that allows developers to build powerful and
user-friendly applications. It provides a flexible development environment, supports multiple
devices, and ensures wide app distribution through the Play Store.

●​ Open-source and free to use


●​ Supports multiple programming languages (Java, Kotlin, etc.)
●​ Large user base across the globe
●​ Easy integration with Google services
●​ Compatible with a wide range of devices

Q4.

a) Develop a program to implement Button, ImageButton, and ToggleButton

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

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />

<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:contentDescription="Image Button" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:textOff="OFF" />
</LinearLayout>

MainActivity.java

package com.example.myapp;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

Button button1;
ImageButton imageButton1;
ToggleButton toggleButton1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button1 = findViewById(R.id.button1);
imageButton1 = findViewById(R.id.imageButton1);
toggleButton1 = findViewById(R.id.toggleButton1);

button1.setOnClickListener(v ->
Toast.makeText(this, "Button Clicked", Toast.LENGTH_SHORT).show());

imageButton1.setOnClickListener(v ->
Toast.makeText(this, "ImageButton Clicked", Toast.LENGTH_SHORT).show());

toggleButton1.setOnCheckedChangeListener((buttonView, isChecked) ->


Toast.makeText(this, isChecked ? "Toggle ON" : "Toggle OFF",
Toast.LENGTH_SHORT).show());
}
}

b) List Android Development Tools

Android Studio – The official IDE for building Android apps, offering powerful code editing,
debugging, and UI design tools.

ADB (Android Debug Bridge) – A command-line tool that allows communication between your
development machine and Android devices.

SDK Manager – Helps download and manage different versions of Android SDK packages.

AVD Manager – Used to create and manage virtual devices (emulators) for testing apps.

Gradle – A build automation system that compiles your code and packages it into an APK.

Lint – Analyzes your code for bugs, performance issues, and coding standard violations.

ProGuard – Optimizes and obfuscates your code to reduce APK size and protect it from
reverse engineering.

Q5.

a) Develop a program to implement a Login Window using above UI controls.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:text="Login Window"
android:textSize="24sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

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

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

<Button
android:id="@+id/loginBtn"
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.vesp.pr_5;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {


EditText username, password;
Button loginBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

username = findViewById(R.id.username);
password = findViewById(R.id.password);
loginBtn = findViewById(R.id.loginBtn);

loginBtn.setOnClickListener(v -> {
String user = username.getText().toString();
String pass = password.getText().toString();

if (user.equals("admin") && pass.equals("1234")) {


Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show();
}
});
}
}

b) List different UI elements and explain ToggleButton

1.​ TextView – Displays text to the user.​

2.​ EditText – Allows the user to input text.​

3.​ Button – Triggers actions when clicked.​

4.​ ImageButton – A button that shows an image instead of text.​

5.​ ToggleButton – Switches between two states (ON/OFF).​

6.​ ProgressBar – Shows loading progress.​

7.​ CheckBox – Selectable boxes used for multi-choice options.​

8.​ RadioButton – Allows selecting one option from a group.​

ToggleButton:

●​ A ToggleButton is a two-state button used to switch between ON and OFF.​

●​ You can set android:textOn and android:textOff for the two states.​

●​ Commonly used to control settings like Wi-Fi or visibility (e.g., show/hide password).​
Q6.

a) Develop a program to implement ProgressBar

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:progress="0" />

<Button
android:id="@+id/startBtn"
android:text="Start Progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />

</LinearLayout>

MainAcitvity.java

package com.vesp.pr_6;

import android.os.Bundle;
import android.widget.Button;
import android.widget.ProgressBar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {


ProgressBar progressBar;
Button startBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

progressBar = findViewById(R.id.progressBar);
startBtn = findViewById(R.id.startBtn);

startBtn.setOnClickListener(v -> {
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
int finalI = i;
runOnUiThread(() -> progressBar.setProgress(finalI));
try {
Thread.sleep(50); // delay to simulate progress
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
});
}
}


b) Enlist the steps to publish the Android application

Android application publishing is a process that makes your Android applications available to
users. Publishing is the last phase of the Android application development process.
1. Open that application project in Android studio and select Build → Generate Signed APK
from your Android studio.
2. Enter your key store path,key store password,key alias and key password to protect your
application.
3. Go to Google Play Console and login with existing google ID if you have any, otherwise you
can create a new Google ID and then register.
4. Accept the Developer agreement (Terms and Conditions)
5. Complete the registration fee process by making a one time payment of $25.
6. Complete Account and application details
7. After registration, upload the release-ready APK of your application.
Q7.

a) Develop a program to implement ListView, GridView, ImageView and ScrollView

activity_main.xml

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


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
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:padding="16dp">

<!-- ListView -->


<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ListView Example"
android:textSize="18sp"
android:paddingBottom="8dp"/>

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="200dp"/>

<!-- GridView -->


<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GridView Example"
android:textSize="18sp"
android:paddingTop="16dp"
android:paddingBottom="8dp"/>

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:numColumns="4"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>

<!-- ImageView -->


<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ImageView Example"
android:textSize="18sp"
android:paddingTop="16dp"
android:paddingBottom="8dp"/>

<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_gravity="center"/>

</LinearLayout>
</ScrollView>

MainActivity.java

package com.vesp.pr_7;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize ListView with a long list


ListView listView = findViewById(R.id.listView);
String[] fruits = {
"Apple", "Banana", "Cherry", "Date", "Fig", "Grapes", "Guava",
"Kiwi", "Lemon", "Mango", "Melon", "Orange", "Papaya", "Peach", "Pear",
"Pineapple", "Plum", "Pomegranate", "Watermelon", "Avocado", "Blackberry",
"Coconut", "Cranberry", "Dragonfruit", "Jackfruit", "Lychee",
"Olive", "Raspberry", "Strawberry"
};

ArrayAdapter<String> listAdapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1, fruits);
listView.setAdapter(listAdapter);

// Initialize GridView with a calculator-like layout (4x5 grid)


GridView gridView = findViewById(R.id.gridView);
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};

ArrayAdapter<String> gridAdapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1, buttons);
gridView.setAdapter(gridAdapter);

gridView.setOnItemClickListener((parent, view, position, id) -> {


String selectedButton = (String) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected: " + selectedButton,
Toast.LENGTH_SHORT).show();
});

// Initialize ImageView (you can use your own image resource here)
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_foreground); // Update with your
image resource
}
}


b) Define Service lifecycle in Android

A Service in Android runs in the background to perform long-running operations. The lifecycle
of a Service involves the following key methods:

Lifecycle Methods of a Service:


1.​ onCreate()​

○​ Called once when the service is first created.​

○​ Use it for one-time setup (e.g., starting threads, initializing resources).​

2.​ onStartCommand()​

○​ Called every time startService() is invoked.​

○​ Contains the code that executes when the service is started.​

3.​ onBind()​

○​ Called when another component binds to the service using bindService().​

○​ Returns an IBinder interface for communication.​

4.​ onUnbind()​

○​ Called when all clients have unbound with unbindService().​

5.​ onDestroy()​

○​ Called when the service is no longer used and is being destroyed.​

○​ Used to clean up any resources.​

Service Lifecycle Flow (Started Service)

onCreate() → onStartCommand() → (service runs) → onDestroy()

Q8.

a) Develop a program to implement new activity using Explicit Intent and Implicit Intent

Here’s a simple Android program that demonstrates both Explicit Intent and Implicit Intent by
launching a new activity and opening a website.
MainActivity.java – Uses both intents:

package com.example.intentsdemo;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

Button btnExplicit, btnImplicit;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnExplicit = findViewById(R.id.btnExplicit);
btnImplicit = findViewById(R.id.btnImplicit);

// Explicit Intent
btnExplicit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent explicitIntent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(explicitIntent);
}
});

// Implicit Intent
btnImplicit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent implicitIntent = new Intent(Intent.ACTION_VIEW);
implicitIntent.setData(Uri.parse("https://www.google.com"));
startActivity(implicitIntent);
}
});
}
}
SecondActivity.java
package com.example.intentsdemo;

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

public class SecondActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}

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:padding="20dp">

<Button
android:id="@+id/btnExplicit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Explicit Intent" />

<Button
android:id="@+id/btnImplicit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Implicit Intent"
android:layout_marginTop="16dp"/>
</LinearLayout>

activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Second Activity!"
android:textSize="20sp" />
</LinearLayout>

Add Second Activity in AndroidManifest.xml

<activity android:name=".SecondActivity"></activity>


b) Give the syntax of the following components:

●​ Activities​

●​ Services​

●​ ContentProviders​

●​ BroadcastReceiver​

1. Activities
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

2. Services
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Service logic here
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null; // For unbound services
}
}

3. ContentProviders
public class MyContentProvider extends ContentProvider {
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(...) { ... }

@Override
public Uri insert(...) { ... }

@Override
public int delete(...) { ... }

@Override
public int update(...) { ... }

@Override
public String getType(Uri uri) { ... }
}

BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Handle broadcast message
}
}

Q9.
a) Develop a program to implement Sensors

[ACCELEROMETER]

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:padding="20dp"
android:gravity="center">

<TextView
android:id="@+id/sensorData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accelerometer Data"
android:textSize="18sp" />
</LinearLayout>

MainActivity.Java

package com.vesp.pr_9;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

private SensorManager sensorManager;


private Sensor accelerometer;
private TextView sensorData;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorData = findViewById(R.id.sensorData);

// Initialize Sensor Manager


sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

// Get Accelerometer Sensor


if (sensorManager != null) {
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
}

@Override
protected void onResume() {
super.onResume();
// Register Listener
if (accelerometer != null) {
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
}

@Override
protected void onPause() {
super.onPause();
// Unregister Listener
sensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

sensorData.setText("Accelerometer Values:\nX: " + x + "\nY: " + y + "\nZ: " + z);


}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Not used in this example
}
}

b) Differentiate between JVM and DVM
Q10.

a) Develop a program to build Camera

AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="true" />

<application
android:requestLegacyExternalStorage="true"
... >

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>

res/xml/file_paths.xml

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


<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="my_images"
path="Pictures" />
</paths>

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:gravity="center"
android:padding="20dp">
<Button
android:id="@+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Image" />

<ImageView
android:id="@+id/imageView"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="20dp"
android:scaleType="centerCrop"
android:contentDescription="Captured Image" />
</LinearLayout>

MainActivity.java

package com.example.cameraapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

Button btnCapture;
ImageView imageView;
String currentPhotoPath;

static final int REQUEST_IMAGE_CAPTURE = 1;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnCapture = findViewById(R.id.btnCapture);
imageView = findViewById(R.id.imageView);

btnCapture.setOnClickListener(v -> dispatchTakePictureIntent());


}

private void dispatchTakePictureIntent() {


Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}

if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
getPackageName() + ".fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}

private File createImageFile() throws IOException {


String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);

currentPhotoPath = image.getAbsolutePath();
return image;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {


File imgFile = new File(currentPhotoPath);
if (imgFile.exists()) {
imageView.setImageURI(Uri.fromFile(imgFile));
}
}
}
}


b) List and explain different types of Android layouts

Android provides various layout types to arrange UI components (views) in an activity. These
layouts define the structure and positioning of child views.

1. LinearLayout

●​ Arranges child views in a single row or column.​

●​ Controlled using android:orientation="vertical" or "horizontal".​

●​ Simple and easy to use for basic UI arrangements.​

2. RelativeLayout (Deprecated)

●​ Positions views relative to each other or parent.​

●​ Allows flexibility like placing a view below, beside, or aligned with another view.​

●​ Replaced by ConstraintLayout for better performance.​

3. ConstraintLayout

●​ Most powerful and flexible layout.​

●​ Uses constraints to position views relative to each other or to the parent.​


●​ Reduces the need for nested layouts and improves app performance.​

●​ Supports complex UI designs.​

4. FrameLayout

●​ Designed to hold a single view, or overlap multiple views.​

●​ Commonly used to display fragments or media content.​

●​ Views are stacked on top of each other like layers.​

5. TableLayout

●​ Organizes views in the form of rows and columns (like a table).​

●​ Each row is defined using a <TableRow>.​

●​ All columns in a row are evenly sized.​

6. GridLayout

●​ Places items in a grid structure (rows and columns).​

●​ More control over view placement than TableLayout.​

●​ You can specify row and column number for each view.​

Conclusion:

Each layout has its own advantages. For simple UIs, LinearLayout is useful. For complex and
performance-optimized layouts, ConstraintLayout is preferred.

Q11.

a) Develop a program for providing Bluetooth connectivity

AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

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:padding="20dp">

<Button
android:id="@+id/btnEnableBluetooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enable Bluetooth" />

<Button
android:id="@+id/btnPairedDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Paired Devices"
android:layout_marginTop="10dp" />

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>

MainActivity.java
package com.example.bluetoothapp;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

BluetoothAdapter bluetoothAdapter;
Button btnEnableBluetooth, btnPairedDevices;
ListView listView;

static final int REQUEST_ENABLE_BT = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnEnableBluetooth = findViewById(R.id.btnEnableBluetooth);
btnPairedDevices = findViewById(R.id.btnPairedDevices);
listView = findViewById(R.id.listView);

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
finish();
}

btnEnableBluetooth.setOnClickListener(v -> {
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
} else {
Toast.makeText(this, "Bluetooth is already enabled", Toast.LENGTH_SHORT).show();
}
});

btnPairedDevices.setOnClickListener(v -> showPairedDevices());


}
private void showPairedDevices() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.BLUETOOTH_CONNECT}, 2);
return;
}

Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();


ArrayList<String> deviceList = new ArrayList<>();

if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceList.add(device.getName() + "\n" + device.getAddress());
}
} else {
deviceList.add("No paired devices found");
}

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1, deviceList);
listView.setAdapter(adapter);
}
}


b) Explain View, ViewGroups, and Activities

In Android development, View, ViewGroup, and Activity are the basic building blocks of the
user interface (UI) and app lifecycle.

1. View

●​ A View is the basic UI component in Android.​

●​ It represents a widget or control that the user can see and interact with.​

●​ Examples: Button, TextView, EditText, ImageView, etc.​

●​ It is responsible for drawing and event handling (like touch, click).​

Example:
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me" />

2. ViewGroup

●​ A ViewGroup is a container that holds multiple Views or other ViewGroups.​

●​ It defines how child views are arranged and displayed on the screen.​

●​ It acts like a layout manager.​

Common ViewGroups:

●​ LinearLayout​

●​ RelativeLayout​

●​ ConstraintLayout​

●​ FrameLayout​

Example:

<LinearLayout

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView android:text="Name" />

<EditText android:hint="Enter name" />


</LinearLayout>

3. Activity

●​ An Activity is a single screen in an Android app.​

●​ It contains the UI layout (views and view groups) and handles user interactions.​

●​ It is a Java or Kotlin class that extends Activity or AppCompatActivity.​

●​ Each activity has its own lifecycle (onCreate, onStart, onResume, etc.)​

Example:

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Q12.

a) Perform AsyncTask using SQLite

MyDatabaseHelper.java

package com.example.sqliteasync;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;

public class MyDatabaseHelper extends SQLiteOpenHelper {


public static final String DB_NAME = "mydb";
public static final String TABLE_NAME = "students";

public MyDatabaseHelper(Context context) {


super(context, DB_NAME, null, 1);
}

public void onCreate(SQLiteDatabase db) {


db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY
AUTOINCREMENT, name TEXT)");
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

public void insertStudent(String name) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
db.insert(TABLE_NAME, null, values);
db.close();
}
}
MainActivity.java
package com.example.sqliteasync;

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

public class MainActivity extends AppCompatActivity {

EditText editText;
Button btnInsert;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText = findViewById(R.id.editTextName);
btnInsert = findViewById(R.id.btnInsert);

btnInsert.setOnClickListener(v -> {
String name = editText.getText().toString().trim();
if (!name.isEmpty()) {
new InsertStudentTask(MainActivity.this).execute(name);
} else {
Toast.makeText(MainActivity.this, "Enter a name", Toast.LENGTH_SHORT).show();
}
});
}

// Inner AsyncTask class


private static class InsertStudentTask extends AsyncTask<String, Void, Void> {
MyDatabaseHelper dbHelper;
Context context;

public InsertStudentTask(Context context) {


this.context = context;
dbHelper = new MyDatabaseHelper(context);
}

@Override
protected Void doInBackground(String... names) {
dbHelper.insertStudent(names[0]);
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(context, "Data inserted", Toast.LENGTH_SHORT).show();
}
}
}
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="16dp">
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />

<Button
android:id="@+id/btnInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert Name"
android:layout_marginTop="10dp" />
</LinearLayout>


b) Describe importance of strings.xml file

In Android development, the strings.xml file is used to store all the text (string) resources
that appear in the user interface. It is located inside the res/values/ directory.

1. Centralized String Management:

All the user-visible strings are defined in one place. This makes it easier to manage and update
the text content of the app.

2. Supports Localization:

The strings.xml file allows translation of the app into different languages by creating
separate files like values-hi/strings.xml for Hindi, values-fr/strings.xml for
French, etc.

3. Improves Code Readability and Maintainability:

Instead of hardcoding strings directly in Java or XML layouts, we use references like
@string/app_name. This keeps the code clean and easy to understand.

4. Avoids Duplication:

If a string is used in multiple places, we can define it once in strings.xml and reuse it, which
avoids repetition.
5. Required for App Configuration:

Important values like the application name are stored here, which are used automatically by the
system.

Example:

<resources>

<string name="app_name">Student App</string>

<string name="welcome">Welcome to the App</string>

<string name="submit">Submit</string>

</resources>

Conclusion:

The strings.xml file is very important in Android as it helps in managing strings efficiently,
supports multiple languages, and keeps the code organized and reusable.

Q13.

a) Create a sample login app:

●​ Check username/password​

●​ On success: Show “Login Successful”​

●​ On fail: Show Toast “Login Fail”​

MainActivity.java

package com.example.loginapp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {

EditText editUsername, editPassword;


Button btnLogin;
TextView textResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editUsername = findViewById(R.id.editUsername);
editPassword = findViewById(R.id.editPassword);
btnLogin = findViewById(R.id.btnLogin);
textResult = findViewById(R.id.textResult);

btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = editUsername.getText().toString();
String pass = editPassword.getText().toString();

if (user.equals("admin") && pass.equals("1234")) {


textResult.setText("Login Successful");
} else {
Toast.makeText(MainActivity.this, "Login Fail", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">

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

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

<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="15dp" />

<TextView
android:id="@+id/textResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_marginTop="20dp" />
</LinearLayout>

Q14.

a) Create login application where Login button is disabled until username and password are
validated

MainActivity.java

package com.example.loginapp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {

EditText editUsername, editPassword;


Button btnLogin;
TextView textResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editUsername = findViewById(R.id.editUsername);
editPassword = findViewById(R.id.editPassword);
btnLogin = findViewById(R.id.btnLogin);
textResult = findViewById(R.id.textResult);

// Initially disable the login button


btnLogin.setEnabled(false);

// Add text change listeners to both fields


editUsername.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int
after) {}

@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count)
{
validateInput();
}

@Override
public void afterTextChanged(Editable editable) {}
});

editPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int
after) {}

@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count)
{
validateInput();
}

@Override
public void afterTextChanged(Editable editable) {}
});

// Set onClickListener for the login button


btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = editUsername.getText().toString();
String pass = editPassword.getText().toString();

if (user.equals("admin") && pass.equals("1234")) {


textResult.setText("Login Successful");
} else {
Toast.makeText(MainActivity.this, "Login Fail", Toast.LENGTH_SHORT).show();
}
}
});
}

// Method to enable or disable the login button based on input validation


private void validateInput() {
String username = editUsername.getText().toString().trim();
String password = editPassword.getText().toString().trim();

if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {


btnLogin.setEnabled(true); // Enable the login button
} else {
btnLogin.setEnabled(false); // Disable the login button
}
}
}

Activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<EditText
android:id="@+id/editUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />

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

<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="15dp"
android:enabled="false" /> <!-- Initially disabled -->

<TextView
android:id="@+id/textResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_marginTop="20dp" />
</LinearLayout>
Q15.

a) Develop a program to:

●​ Send SMS​

●​ Receive SMS​

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsapp">

<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.DayNight">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<!-- Define BroadcastReceiver for SMS reception -->


<receiver android:name=".SMSReceiver" android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>

</application>
</manifest>

MainActivity.java
package com.example.smsapp;

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

public class MainActivity extends AppCompatActivity {

EditText phoneNumberEditText, messageEditText;


Button sendButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

phoneNumberEditText = findViewById(R.id.phoneNumberEditText);
messageEditText = findViewById(R.id.messageEditText);
sendButton = findViewById(R.id.sendButton);

sendButton.setOnClickListener(v -> {
String phoneNumber = phoneNumberEditText.getText().toString();
String message = messageEditText.getText().toString();

if (!phoneNumber.isEmpty() && !message.isEmpty()) {


sendSMS(phoneNumber, message);
} else {
Toast.makeText(MainActivity.this, "Please enter both phone number and message",
Toast.LENGTH_SHORT).show();
}
});
}

private void sendSMS(String phoneNumber, String message) {


SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(MainActivity.this, "SMS Sent!", Toast.LENGTH_SHORT).show();
}
}
SMSReceiver.java

package com.example.smsapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// Get the SMS message from the Intent
Bundle bundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "";
if (bundle != null) {
// Retrieve the SMS messages
Object[] pdus = (Object[]) bundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "From: " + messages[i].getOriginatingAddress() + "\n";
strMessage += "Message: " + messages[i].getMessageBody() + "\n\n";
}
// Display the received message as a Toast
Toast.makeText(context, "Received SMS: " + strMessage,
Toast.LENGTH_LONG).show();
}
}
}

Activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<EditText
android:id="@+id/phoneNumberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Phone Number"
android:inputType="phone"/>

<EditText
android:id="@+id/messageEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Message"
android:inputType="textMultiLine"
android:layout_marginTop="10dp"/>

<Button
android:id="@+id/sendButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_marginTop="15dp"/>

</LinearLayout>

Q16.

a) Develop a program to send and receive email

In your build.gradle file:

dependencies {

implementation 'com.sun.mail:android-mail:1.6.0'

implementation 'com.sun.mail:android-activation:1.6.0'

MainActivity.java

package com.example.sms;

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

public class MainActivity extends AppCompatActivity {

private EditText mEditTextTo, mEditTextSubject, mEditTextMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mEditTextTo = findViewById(R.id.edit_text_to);
mEditTextSubject = findViewById(R.id.edit_text_subject);
mEditTextMessage = findViewById(R.id.edit_text_message);

Button buttonSend = findViewById(R.id.button_send);


buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMail();
}
});
}

private void sendMail() {


String recipientList = mEditTextTo.getText().toString();
String[] recipients = recipientList.split(",");
String subject = mEditTextSubject.getText().toString();
String message = mEditTextMessage.getText().toString();

Intent intent = new Intent(Intent.ACTION_SEND);


intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.setType("message/rfc822");

// Launch email client chooser


startActivity(Intent.createChooser(intent, "Choose an Email client"));
}
}
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:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To:"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subject:"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_text_subject"
android:inputType="textEmailSubject" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message:"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />

<EditText
android:id="@+id/edit_text_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start|top"
android:lines="10" />

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

</LinearLayout>

Q17.

a) Deploy map-based application – Part I: Current Location

Activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
android:id="@+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

Strings.xml

<resources>
<string name="app_name">MapApp</string>
<string name="map_key"
translatable="false">AIzaSyB_qsP8AOP_P0MdlPz-48TDaJYjTP3vbjo</string>
</resources>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
android:allowBackup="true"
android:label="Map App"
android:theme="@android:style/Theme.DeviceDefault">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/map_key" />

<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>

build.gradle.kts(:app)

plugins {
id("com.android.application")
}

android {
namespace = "com.example.map"
compileSdk = 33

defaultConfig {
applicationId = "com.example.map"
minSdk = 21
targetSdk = 33
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}

compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}

dependencies {
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.9.0")
implementation("com.google.android.gms:play-services-maps:18.1.0")
implementation("com.google.android.gms:play-services-location:21.0.1")
}

MainActivity.java

package com.example.map;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

FusedLocationProviderClient fusedLocationProviderClient;
Location currentLocation;
private static final int REQUEST_CODE = 101;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}

private void fetchLastLocation() {


if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
return;
}

Task<Location> task = fusedLocationProviderClient.getLastLocation();


task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(getApplicationContext(), "Lat: " +
currentLocation.getLatitude() + " Long: " +
currentLocation.getLongitude(),
Toast.LENGTH_SHORT).show();
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.google_map);
mapFragment.getMapAsync(MainActivity.this);
}
}
});
}

@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here");
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(markerOptions);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
}
}

You might also like