Android
Android
I. Theory:
III. Exercise
I. Theory:
Android is based on Linux with a set of native core C/C++ libraries. Android
applications are written in Java. However, they run on Android's own Java Virtual
Machine, called Dalvik Virtual Machine (DVM) (instead of JDK's JVM) which is
optimized to operate on the small and mobile devices. SDK provides a selection of
tools required to build Android apps or to ensure the process goes as smoothly as
possible. Whether creating an app with Java, Kotlin or C#, SDK should run on an
Android device and access unique features of the OS.
Step 1 - Setup Java Development Kit (JDK) You can download the latest version
of Java JDK from Oracle's Java site: Java SE Downloads. You will find
instructions for installing JDK in downloaded files, follow the given instructions to
install and configure the setup. Finally, set PATH and JAVA_HOME environment
variables to refer to the directory that contains java and javac, typically
java_install_dir/bin and java_install_dir respectively. If you are running Windows
and have installed the JDK in C:\jdk1.6.0_15, you would have to put the following
line in your C:\autoexec.batfile.
set
PATH=C:\jdk1.6.0_15\bin; %PATH% set JAVA_HOME=C:\jdk1.6.0_15
Step 2 - Setup Android SDK You can download the latest version of Android SDK
from Android’s official website: http://developer.android.com/sdk/index.html. If
you are installing SDK on Windows machine, then you will find ainstaller_rXX
windows.exe, so just download and run this exe which will launch Android SDK
Tool Setup wizard to guide you throughout the installation, so just follow the
instructions carefully. Finally, you will have Android SDK Tools installed on your
machine. If you are installing SDK either on Mac OS or Linux, check the
instructions provided along with the downloaded android-sdk_rXX-macosx.zip file
for Mac OS and android sdk_rXX-linux.tgz file for Linux. This tutorial will
consider that you are going to setup your environment on Windows machine
having Windows 7 operating system.
Step 3 - Setup Android Development Tools (ADT) Plugin This step will help you
in setting Android Development Tool plugin for Eclipse. Let's start with launching
Eclipse and then, choose Help > Software Updates > Install New Software. This
will display the following dialogue box.
Step 4 - Create Android Virtual Device to test your Android applications you will
need a virtual Android device. So before we start writing our code, let us create an
Android virtual device. Launch Android AVD Manager using Eclipse menu
options Window > AVD Manager> which will launch Android AVD Manager. Use
New button to create a new Android Virtual Device and enter the following
information, before clicking Create AVD button.
2. List various IDEs that can be used to execute android operating system.
Ans:
1. Android Studio
2. Eclipse with ADT (Android Development Tools)
3. IntelliJ IDEA
4. Visual Studio with Xamarin
5. NetBeans
6. Unity with Android Build Support
III. Exercise
The executable file for the device The executable file for the device
is .jar file. is .apk file.
I. Theory:
Configuration set up steps should be known beforehand as learnt in the practical no.2
Android Development Tools (ADT) is a plugin for the Android studio that is designed
to give you a powerful, integrated environment in which to build Android
applications. ADT extends the capabilities of Android studio to let you quickly set up
new Android projects, create an application UI, add components based on the Android
Framework API, debug your applications using the Android SDK tools, and even
export signed (or unsigned) APKs in order to distribute your application. Developing
in Android studio with ADT is highly recommended and is the fastest way to get
started. With the guided project setup, it provides, as well as tools integration, custom
XML editors, and debug output pane, ADT gives you an incredible boost in
developing Android applications.
Setting up Android Development Tools (ADT)
Get Android Development Tools (ADT) from ADT Bundle
The ADT Bundle includes everything you need to begin developing apps:
• Android studio + ADT plugin
• Android SDK Tools Android Platform-tools
• The latest Android platform
• The latest Android system image for the emulator
III. Exercise
I. Theory:
In android studio students must be aware of the directory structure and the control
flow of the program. Program should be either executed on the android mobile phones
or on the suitable emulators. To execute a simple program, like to display Hello World
on screen syntax of writing a program in android is pre-requisite as the programming
language used is JAVA only. The main activity code is a Java file MainActivity.java.
This is the actual application file which ultimately gets converted to a Dalvik
executable and runs your application.
Following is the default code generated by the application wizard for Hello World!
application:
package com.example.helloworld; import android.os.Bundle;
import android.app.Activity; import android.view.Menu; import
android.view.MenuItem;
import android.support.v4.app.NavUtils; public class MainActivity extends
Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main,menu);
return true;
}
}
The Manifest File: Whatever component you develop as a part of your application,
you must declare all its components in a manifest file called AndroidManifest.xml
which resides at the root of the application project directory. This file works as an
interface between Android OS and your application, so if you do not declare your
component in this file, then it will not be considered by the OS. The <activity> tag is
used to specify an activity and android:name attribute specifies the fully qualified
class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity>
tags. The action for the intent filter is named android.intent.action.MAIN to indicate
that this activity serves as the entry point for the application. The category for the
intent- filter is named android.intent.category.LAUNCHER to indicate that the
application can be launched from the device's launcher icon. The @string refers to the
strings.xml file explained below. Hence, @string/app_name refers to the app_name
string defined in the strings.xml file, which is "HelloWorld". Similar way, other
strings get populated in the application. Following is the list of tags which you will
use in your manifest file to specify different Android application components:
1) <activity>elements for activities
2) <service> elements for services
3) <receiver> elements for broadcast receivers
4) <provider> elements for content providers
Practicalno1.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno1);
}
}
activity_practicalno1.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
IV. Output
V. Marks Obtained
I. Theory:
To develop and place the android components accurately on the display screen,
android provides various layout managers. Layout managers can be used on the
simple android program too. Various layout managers can be selected as per the
program requirements.
Layouts which are subclasses of View Group class and a typical layout defines
the visual structure for an Android user interface and can be created either at run
time using View/View Group objects or you can declare your layout using
simple XML file main_layout.xml which is located in the res/layout folder of
your project. layouts defined in XML file. A layout may contain any type of
widgets such as buttons, labels, textboxes etc. Layout Attributes Each layout has
a set of attributes which define the visual properties of that layout. There are
few common attributes among all the layouts and there are other attributes
which are specific to that layout. Types of layouts are Linear and Absolute
layouts.
Linear Layout: -
Practicalno5.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno5 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno5);
}
}
activity_practicalno5.xml
1. Linear Layout: -
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
2. AbsoluteLayout
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter your age"
android:layout_x="100dp"
android:layout_y="150dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_x="100dp"
android:layout_y="200dp" />
</AbsoluteLayout>
IV. Output
V. Marks Obtained
I. Theory:
To develop and place the android components accurately on the display screen,
android provides various layout managers. Layout managers can be used on the
simple android program too. Various layout managers can be selected as per the
program requirements.
1. Frame Layout:
Frame Layout is designed to block out an area on the screen to display a single
item. Generally, Frame Layout should be used to hold a single child view,
because it can be difficult to organize child views in a way that's scalable to
different screen sizes without the children overlapping each other. You can,
however, add multiple children to a Frame Layout and control their position
within the Frame Layout by assigning gravity to each child, using the android:
layout gravity attribute. Child views are drawn in a stack, with the most recently
added child on top. The size of the Frame Layout is the size of its largest child
(plus padding), visible or not (if the Frame Layout's parent permits).
2. Relative Layout:
A Relative Layout is a very powerful utility for designing a user interface
because it can eliminate nested view groups and keep your layout hierarchy flat,
which improves performance. If you find yourself using several nested Linear
Layout groups, you may be able to replace them with a single Relative Layout.
3. Table Layout:
A Table Layout consists of a number of Table Row objects, each defining a row
(actually, you can have other children, which will be explained below). Table
Layout containers do not display border lines for their rows, columns, or cells.
Each row has zero or more cells; each cell can hold one View object. The table
has as many columns as the row with the most cells. A table can leave cells
empty. Cells can span columns, as they can in HTML. The width of a column is
defined by the row with the widest cell in that column.
Practicalno6.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno6 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno6);
}
}
activity_practicalno6.xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#FFC107"
android:layout_marginBottom="16dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"/>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_gravity="center"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FrameLayout Example"
android:layout_gravity="top|center"/>
</FrameLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#4CAF50"
android:layout_marginBottom="16dp">
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher_foreground"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TableLayout Example"/>
</TableRow>
</TableLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#2196F3">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"/>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_centerInParent="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RelativeLayout Example"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="16dp"/>
</RelativeLayout>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
In this practical, UI controls in android like Text view and edit view are studied.
Wherein the UI controls can be developed, used and placed on the screen using
different layout managers as per the problem statement requirements.
1. Text View:
In Android, Text View displays text to the user and optionally allows them to edit it
programmatically. Text View is a complete text editor; however basic class is
configured to not allow editing but we can edit it. View is the parent class of Text
View Being a subclass of view the text view component can be used in your app’s.
GUI inside a View Group, or as the content view of an activity. We can create a Text
View instance by declaring it inside a layout (XML file) or by instantiating it
programmatically (Java Class).
2. Edit Text:
In Android, Edit Text is a standard entry widget in android apps. It is an overlay over
Text View that configures itself to be editable. Edit Text is a subclass of Text View
with text editing operations. Often use Edit Text in our applications in order to provide
an input or text field, especially in forms. The simplest example of Edit Text is Login
or Sign-in form. Text Fields in Android Studio are basically Edit Text.
Practicalno7.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno7 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno7);
}
}
activity_practicalno7.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Enter your text:"/>
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type here"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
In this practical, UI controls in android like Text view and edit view are studied.
Wherein the UI controls can be developed, used and placed on the screen using
different layout managers as per the problem statement requirements.
Auto Complete Text View:
Android Auto Complete Text View completes the word based on the reserved words,
so no need to write all the characters of the word. Android Auto Complete Text View
is an editable text field, it displays a list of suggestions in a drop-down menu from
which user can select only one suggestion or value. Android Auto Complete Text View
is the subclass of Edit Text class. The Multi Auto Complete Text View is the subclass
of AutoComplete Text View class. An editable text view that shows completion
suggestions automatically while the user is typing. The list of suggestions is displayed
in a drop-down menu from which the user can choose an item to replace the content of
the edit box. The drop down can be dismissed at any time by pressing the back key or,
if no item is selected in the drop down, by pressing the enter centre key. The list of
suggestions is obtained from a data adapter and appears only after a given number of
characters defined by the threshold. Auto Complete Text View is a component used to
show suggestions while writing in an editable text field. The suggestions list is shown
in a drop-down menu from which a user can select the desired item. The list of
suggestions is obtained from an adapter and it appears only after a number of
characters that are specified in the threshold. To use an Auto Complete Threshold
field, it needs to be defined in the layout.
Practicalno8.java
package com.hdm.harshalmakodepractical;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
activity_practicalno8.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your text:"/>
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type here"/>
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select a country"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
In this practical, UI controls in android like Buttons are studied. There are various
types of buttons like Image button and toggle button which is studied.
1. Buttons-
In Android, Button represents a push button. The android. widget. Button is subclass
of Text View class and Compound Button is the subclass of Button class. A Push
buttons can be clicked, or pressed by the user to perform an action. There are different
types of buttons used in android such as Compound Button, Toggle Button, Radio
Button. Button is a subclass of Text View class and compound button is the subclass
of Button class. On a button we can perform different actions or events like click
event, pressed event, touch event etc. Android buttons are GUI components which are
sensible to taps (clicks) by the user. When the user taps/clicks on button in an Android
app, the app can respond to the click/tap. These buttons can be divided into two
categories: the first is Buttons with text on, and second is buttons with an image on.
2. Types of buttons–
Buttons can be divided into two categories the first is Buttons with text on, and second
is buttons with an image on.
3. Image Button –
A button with images on can contain both an image and a text. Android buttons with
images on are also called Image Button. In Android, Image Button is used to display a
normal button with a custom image in a button. In simple words we can say, Image
Button is a button with an image that can be pressed or clicked by the users. By
default it looks like a normal button with the standard button background that changes
the color during different button states. An image on the surface of a button is defined
within a xml (i.e. layout ) by using src attribute or within java class by using
setImageResource() method. We can also set an image or custom drawable in the
background of the image button . Image Button has all the properties of a normal
button so you can easily perform any event like click or any other event which you
can perform on a normal button.
Note: Standard button background image is displayed in the background of button
whenever you create an image button. To remove that image, you can define your own
background image in xml by using background attribute or in java class by using
setBackground() method.
4. Toggle Button-
A toggle button allows the user to change a setting between two states. You can add a
basic toggle button to your layout with the Toggle Button object. If you need to
change a button's state yourself, you can use the Compound Button.setChecked() or
Compound Button.toggle() method. To detect when the user activates the button or
switch, create a Compound Button. OnCheckedChangeListener object and assign it to
the button by calling setOnCheckedChangeListener().
It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wi-Fi, Bluetooth etc. By default, the android Toggle Button will be in
OFF (Unchecked) state. We can change the default state of Toggle Button by using
android:checked attribute. In case, if we want to change the state of Toggle Button to
ON (Checked), then we need to set android:checked = "true" in our XML layout file.
Practicalno9.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ToggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno9);
Button button = findViewById(R.id.button);
ImageButton imageButton = findViewById(R.id.imageButton);
ToggleButton toggleButton = findViewById(R.id.toggleButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno9.this, "Button Clicked",
Toast.LENGTH_SHORT).show();
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno9.this, "ImageButton Clicked",
Toast.LENGTH_SHORT).show();
}
});
toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (toggleButton.isChecked()) {
Toast.makeText(practicalno9.this, "ToggleButton Checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno9.this, "ToggleButton Unchecked",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
activity_practicalno9.xml
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_marginTop="20dp"/>
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:layout_marginTop="20dp"
android:background="#5C24AA"
/>
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle"
android:layout_marginTop="20dp"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
In this practical, all the previous UI controls in android like Text View, Edit Text
Buttons which are studied are implemented in this practical. Events are also handled
on the android UI controls used in the practical.
Practicalno10.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno10);
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
textViewResult = findViewById(R.id.textViewResult);
}
activity_practicalno10.xml
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:padding="10dp"/>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:padding="10dp"
android:inputType="textPassword"/>
<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="20dp"
android:padding="10dp"
android:onClick="onLoginButtonClick"/>
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text=""
android:textSize="18sp"
android:layout_gravity="center"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
Android CheckBox is a type of two state button either checked or unchecked. There
can be a lot of usage of checkboxes. For example, it can be used to know the hobby of
the user, activate/deactivate the specific action etc.
Practicalno11.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno11);
javaCheckbox = findViewById(R.id.javaCheckbox);
pythonCheckbox = findViewById(R.id.pythonCheckbox);
kotlinCheckbox = findViewById(R.id.kotlinCheckbox);
cSharpCheckbox = findViewById(R.id.cSharpCheckbox);
javascriptCheckbox = findViewById(R.id.javascriptCheckbox);
javaCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(javaCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "Java is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "Java is unchecked",
Toast.LENGTH_SHORT).show();
}
}
});
pythonCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(pythonCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "Python is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "Python is unchecked",
Toast.LENGTH_SHORT).show();
}
}
});
kotlinCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(kotlinCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "Kotlin is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "Kotlin is unchecked",
Toast.LENGTH_SHORT).show();
} }
});
cSharpCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(cSharpCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "C# is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "C# is unchecked",
Toast.LENGTH_SHORT).show();
} }
});
javascriptCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(javascriptCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "JavaScript is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "JavaScript is unchecked",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
activity_practicalno11.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select the languages:"
android:textSize="30sp"/>
<CheckBox
android:id="@+id/javaCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:textSize="20sp"/>
<CheckBox
android:id="@+id/pythonCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Python"
android:textSize="20sp"/>
<CheckBox
android:id="@+id/kotlinCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kotlin"
android:textSize="20sp"/>
<CheckBox
android:id="@+id/cSharpCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C#"
android:textSize="20sp"/>
<CheckBox
android:id="@+id/javascriptCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JavaScript"
android:textSize="20sp"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
Radio Buttons are used when we need to select only one item from a list of presented
items. If Radio Buttons are in Radio Group, when one Radio Button within a group is
selected, all others are automatically deselected. Android Checkbox class is the
subclass of Compound Button class.
Radio Button is generally used with Radio Group. Radio Group is a set of radio
buttons, marking one radio button as checked makes all other radio buttons as
unchecked. A radio button consists of two states – checked and unchecked. Clicking
an unchecked button changes its state to “checked” state and “unchecked” for the
previously selected radio button. To toggle a checked state to unchecked state, we
need to choose another item.
Following are the important attributes related to Radio Group control.
1. android:checkedButton : This is the id of child radio button that should be checked
by default within this radio group.
2. android:orientation : This property on the Radio group defines the orientation to
position its child view consisting of Radio Buttons.
Following are the few methods of radio button:
1. check(id): This sets the selection to the radio button whose identifier is
passed in parameter. -1 is used as the selection identifier to clear the selection.
2. clearCheck() : It clears the selection. When the selection is cleared, no radio
button in this group is selected and getCheckedRadioButtonId() returns null.
3. getCheckedRadioButtonId() : It returns the identifier of the selected radio
button in this group. If its empty selection, the returned value is-1.
4. setOnCheckedChangeListener(): This registers a callback to be invoked
when the checked radio button changes in this group. We must supply instance
of Radio Group. OnCheckedChangeListener to setOnCheckedChangeListener()
method.
Practicalno12.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno12);
radioButton1 = findViewById(R.id.radioButton1);
radioButton2 = findViewById(R.id.radioButton2);
radioButton3 = findViewById(R.id.radioButton3);
radioButton4 = findViewById(R.id.radioButton4);
radioGroup = findViewById(R.id.radioGroup);
radioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno12.this, "Selected Radio Button 1",
Toast.LENGTH_SHORT).show();
}
});
radioButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno12.this, "Selected Radio Button 2",
Toast.LENGTH_SHORT).show();
}
});
radioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int i) {
RadioButton selectedRadioButton = findViewById(i);
String selectedText = selectedRadioButton.getText().toString();
Toast.makeText(practicalno12.this, "Selected: " + selectedText,
Toast.LENGTH_SHORT).show();
}
});
}
}
activity_practicalno12.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Single Radio Buttons"
android:textSize="20sp"
android:textAlignment="center"
/>
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button 1" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button 2" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Radio Button inside RadioGroup"
android:textSize="20sp"
android:textAlignment="center"
android:layout_marginTop="20dp"
/>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
Progress bars are used to show progress of a task. For example, when you are
uploading or downloading something from the internet, it is better to show the
progress of download/upload to the user. In android there is a class called Progress
Dialog that allows you to create progress bar.
A user interface element that indicates the progress of an operation. For a visual
overview of the difference between determinate and indeterminate progress modes,
see Progress & activity. Display progress bars to a user in a non-interruptive way.
Progress bar supports two modes to represent progress: determinate and
indeterminate.
Indeterminate Progress
Use indeterminate mode for the progress bar when you do not know how long an
operation will take. Indeterminate mode is the default for progress bar and shows a
cyclic animation without a specific amount of progress indicated.
Determinate Progress
Use determinate mode for the progress bar when you want to show that a specific
quantity of progress has occurred. For example, the percent remaining of a file being
retrieved, the amount records in a batch written to database, or the percent remaining
of an audio file that is playing.
Progress Dialog is a class that allows you to create progress bar. In order to do this,
you need to instantiate an object of this class. Its syntax is.
ProgressDialog dialog = new ProgressDialog(this);
Practicalno13.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno13);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(practicalno13.this, practicalno13_1.class);
startActivity(i);
}
},5000);
}
}
Practicalno13_1.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno131);
b1 = findViewById(R.id.b1);
Handler handler = new Handler();
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialog dialog=new ProgressDialog(practicalno13_1.this);
dialog.setCancelable(true);
dialog.setMessage("File downloading....");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 100;i++){
finalI = i;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
dialog.setProgress(finalI);
}
});
if(i == 99){
handler.post(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
}
}
}
}).start();
}
});
}
}
activity_practicalno13.xml
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading...."
android:layout_marginTop="20dp"
android:textSize="30dp"
android:textStyle="bold" />
</LinearLayout>
activity_practicalno131.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOWNLOAD FILE"
android:id="@+id/b1"
/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
A View occupies a rectangular area on the screen and is responsible for drawing and
event handling. View is the base class for widgets, which are used to create interactive
UI components (buttons, text fields, etc.). The View Group subclass is the base class
for layouts, which are invisible containers that hold other Views (or other View
Groups) and define their layout properties.
List View
List of scrollable items can be displayed in Android using List View. It helps you to
displaying the data in the form of a scrollable list. Users can then select any list item
by clicking on it. List View is default scrollable so we do not need to use scroll View
or anything else with List View.
List View is widely used in android applications. A very common example of List
View is your phone contact book, where you have a list of your contacts displayed in a
List View and if you click on it then user information is displayed.
Grid View
In android Grid View is a view group that display items in two-dimensional scrolling
grid (rows and columns), the grid items are not necessarily predetermined but they are
automatically inserted to the layout using a List Adapter. Users can then select any
grid item by clicking on it. Grid View is default scrollable so we don't need to use
Scroll View or anything else with Grid View.
Image View
In Android, Image View class is used to display an image file in application. Image
file is easy to use but hard to master in Android, because of the various screen sizes in
Android devices. An android is enriched with some of the best UI design widgets that
allows us to build good looking and attractive UI based application.
Scroll View
In android scroll View can hold only one direct child. This means that, if you have
complex layout with more views (Buttons, Text Views or any other view) then you
must enclose them inside another standard layout like Table Layout, Relative Layout
or Linear Layout. You can specify layout_width and layout_height to adjust width and
height of screen. You can specify height and width in dp(density pixel) or px(pixel).
Then after enclosing them in a standard layout, enclose the whole layout in scroll
View to make all the element or views scrollable.
Practicalno14.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno14);
lv = findViewById(R.id.lv);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = adapter.getItem(position);
Toast.makeText(practicalno14.this,value,Toast.LENGTH_SHORT).show();
}
});
}
}
Practicalno14_1.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno141);
gv = findViewById(R.id.gv);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,subject);
gv.setAdapter(adapter);
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = adapter.getItem(position);
Toast.makeText(practicalno14_1.this,value,
Toast.LENGTH_SHORT).show();
}
});
}
}
activity_practicalno14.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"
tools:context=".practicalno14"
android:orientation="vertical">
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_practicalno141.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"
tools:context=".practicalno14_1"
android:orientation="vertical"
android:gravity="center">
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gv"
android:numColumns="3"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
An Android Toast is a small message displayed on the screen, similar to a tool tip or
other similar popup notification. Android Toast can be used to display information for
the short period of time. A toast contains message to be displayed quickly and
disappears after sometime. It provides simple feedback about an operation in a small
popup. A Toast is displayed on top of the main content of an activity. For example,
navigating away from an email before you send it triggers a "Draft saved toast to let
you know that you can continue editing later.
A toast provides simple feedback about an operation in a small popup. It only fills the
amount of space required for the message and the current activity remains visible and
interactive. Toasts automatically disappear after a timeout.
For example, clicking Send button on an email trigger a "Sending message..." toast
Following is the example to create a toast.
Toast toast = Toast.makeText(getApplicationContext(),
"This is a message displayed in a Toast",
Toast.LENGTH_SHORT); toast.show();
The Toast.makeText() method is a factory method which creates a Toast object. The
method takes 3 parameters. First the methods need a Context object which is obtained
by calling getApplicationContext(). Note: The getApplicationContext() method is a
method that exists inside activities, so the above code has to be located in an Activity
subclass to work.
The second parameter is the text to be displayed in the Toast. The third parameter is
the time duration the Toast is to be displayed.
Practicalno15.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
Button orderButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno15);
checkBox1 = findViewById(R.id.checkBox1);
checkBox2 = findViewById(R.id.checkBox2);
checkBox3 = findViewById(R.id.checkBox3);
orderButton = findViewById(R.id.orderButton);
if (checkBox1.isChecked()) {
selectedItems.append("Item 1: Rs. 10.0\n");
}
if (checkBox2.isChecked()) {
selectedItems.append("Item 2: Rs. 15.0\n");
}
if (checkBox3.isChecked()) {
selectedItems.append("Item 3: Rs. 20.0\n");
}
if (selectedItems.length() > 0) {
selectedItems.deleteCharAt(selectedItems.length() - 1);
Toast.makeText(this, "Selected Items and Prices:\n" + selectedItems.toString(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No items selected", Toast.LENGTH_SHORT).show();
}
}
activity_practicalno15.xml
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1"
android:layout_marginBottom="8dp"/>
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 2"
android:layout_marginBottom="8dp"/>
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 3"
android:layout_marginBottom="16dp"/>
<Button
android:id="@+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"/>
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
Android provides controls for the user to pick a time or pick a date as ready-to-use
dialogs. Each picker provides controls for selecting each part of the time (hour,
minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that
your users can pick a time or date that is valid, formatted correctly, and adjusted to the
user's locale.
Date Picker:
Android Date Picker allows you to select the date consisting of day, month and year in
your custom user interface. For this functionality android provides DatePicker and
DatePickerDialog components.
Time Picker:
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM
mode. The time consists of hours, minutes and clock format. Android provides this
functionality through TimePicker class. Following xml attribute is used to create time
picker.
Practicalno16.java
package com.hdm.harshalmakodepractical;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class practicalno16 extends AppCompatActivity {
Button btnDatePicker, btnTimePicker;
EditText txtDate, txtTime;
private int mYear, mMonth, mDay, mHour, mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno16);
btnDatePicker=(Button)findViewById(R.id.btn_date);
btnTimePicker=(Button)findViewById(R.id.btn_time);
txtDate=(EditText)findViewById(R.id.in_date);
txtTime=(EditText)findViewById(R.id.in_time);
btnDatePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
btnTimePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
activity_practicalno16.xml
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_date"
android:layout_marginTop="82dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT DATE"
android:id="@+id/btn_date"
android:layout_alignBottom="@+id/in_date"
android:layout_toRightOf="@+id/in_date"
android:layout_toEndOf="@+id/in_date" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_time"
android:layout_below="@+id/in_date"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT TIME"
android:id="@+id/btn_time"
android:layout_below="@+id/btn_date"
android:layout_alignLeft="@+id/btn_date"
android:layout_alignStart="@+id/btn_date" />
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
An activity represents a single screen with a user interface. For example, an email
application might have one activity that shows a list of new emails, another activity to
compose an email, and one for reading emails.
Practicalno16.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno17);
Log.d(TAG, "onCreate: Activity created");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: Activity started");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: Activity resumed");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: Activity paused");
}
@Override
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: Activity destroyed");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: Activity restarted");
}
}
IV. Output
V. Marks Obtained
I. Theory:
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc. It facilitates communication
between different android components.
Android application components can connect to other Android applications. This
connection is based on a task description represented by an Intent object.
Intents are asynchronous messages which allow application components to request
functionality from other Android components. Intents allow you to interact with
components from the same applications as well as with components contributed by
other applications. For example, an activity can start an external activity for taking a
picture.
Mostly Intents are used for:
a. For Launching an Activity
b. To start a New Service
c. For Broadcasting Messages
d. To Display a list of contacts in List View
Types of intents:
There are two types of intents
a. Implicit Intent
b. Explicit Intent
Implicit Intent:
The implicit intent is the intent where instead of defining the exact components, you
define the action that you want to perform for different activities.
Syntax:
Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);
Explicit Intent:
An explicit intent is an Intent where you explicitly define the component that needs to
be called by the Android System. An explicit intent is one that you can use to launch a
specific app component, such as a particular activity or service in your app.
Syntax:
Intent I = new
Intent(getApplicationContext(), NextActivity.class);
I.putExtra("value1", "This value for Next Activity");
I.putExtra("value2", "This value for Next Activity");
Practicalno18.java
package com.hdm.harshalmakodepractical;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno18);
numberInput = findViewById(R.id.editTextNumber);
factorialButton = findViewById(R.id.factorialButton);
factorialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inputStr = numberInput.getText().toString();
if (!inputStr.isEmpty()) {
int number = Integer.parseInt(inputStr);
Intent intent = new Intent(practicalno18.this, practicalno18_1.class);
intent.putExtra("NUMBER", number);
startActivity(intent);
}
}
});
}
}
Practicalno18_1.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno181);
resultTextView = findViewById(R.id.resultTextView);
long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
activity_practicalno18.xml
<EditText
android:id="@+id/editTextNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number" />
<Button
android:id="@+id/factorialButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/editTextNumber"
android:text="Factorial"
android:layout_marginLeft="15dp"/>
</RelativeLayout>
activity_practicalno18_1.xml
<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="18sp" />
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
Content_Provider.java
package com.hdm.harshalmakodepractical;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashMap;
public Content_Provider() {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
@Override
public boolean onCreate() {
MyProductDatabaseHelper dbHelper = new
MyProductDatabaseHelper(getContext());
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
} else return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable
String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
if (uriMatcher.match(uri) == uriCode) {
queryBuilder.setProjectionMap(values);
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
Cursor cursor =
queryBuilder.query(db, projection, selection, selectionArgs, null, null,
sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
long rowID = db.insert(TABLE_NAME, "", contentValues);
if (rowID > 0) {
Uri tempUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(tempUri, null);
return tempUri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues,
@Nullable String selection, @Nullable String[] selectionArgs) {
int count;
if (uriMatcher.match(uri) == uriCode) {
count = db.update(TABLE_NAME, contentValues, selection, selectionArgs);
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable
String[] selectionArgs) {
int count;
if (uriMatcher.match(uri) == uriCode) {
count = db.delete(TABLE_NAME, selection, selectionArgs);
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
if (uriMatcher.match(uri) == uriCode) {
return "vnd.android.cursor.dir/products";
} else {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
/*
* Database helper class
* */
private class MyProductDatabaseHelper extends SQLiteOpenHelper {
//sql query to create a new table
String CREATE_DB_TABLE =
(" CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY
KEY AUTOINCREMENT, name TEXT NOT NULL, price NUMBER NOT
NULL);");
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int
newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(database);
}
}
}
Practicalno19.java
package com.hdm.harshalmakodepractical;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno19);
productNameEditText = findViewById(R.id.productNameEditText);
productPriceEditText = findViewById(R.id.productPriceEditText);
addProductButton = findViewById(R.id.addProductButton);
b1 = findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addProductButton.setOnClickListener(view -> {
//get product name and price
String productName = productNameEditText.getText().toString();
String productPrice = productPriceEditText.getText().toString();
Practicalno19.java
package com.hdm.harshalmakodepractical;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno191);
refreshButton = findViewById(R.id.refreshButton);
myTextView = findViewById(R.id.myTextView);
refreshButton.setOnClickListener(view -> {
stringBuilder.append(cursor.getString(cursor.getColumnIndexOrThrow("id")));
stringBuilder.append("\t");
stringBuilder.append("\t");
stringBuilder.append("Name: ");
stringBuilder.append(cursor.getString(cursor.getColumnIndexOrThrow("name")));
stringBuilder.append("\t");
stringBuilder.append("\t");
stringBuilder.append("Price: ");
stringBuilder.append(cursor.getString(cursor.getColumnIndexOrThrow("price")));
stringBuilder.append("\n");
stringBuilder.append("\n");
} while (cursor.moveToNext());
//close the cursor object
cursor.close();
} else {
stringBuilder.append("Noting to show");
}
//set string value in textView
myTextView.setText(stringBuilder);
});
}
}
activity_practicalno19.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:orientation="vertical"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp">
<EditText
android:id="@+id/productNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Product Name"
android:inputType="textPersonName"
tools:ignore="Autofill" />
<EditText
android:id="@+id/productPriceEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Enter Product Price"
android:inputType="numberDecimal"
tools:ignore="Autofill" />
<Button
android:id="@+id/addProductButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textColor="@color/white"
android:textAlignment="center"
android:text="Add New Product" />
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show result"
android:layout_marginTop="15dp"/>
</LinearLayout>
</RelativeLayout>
activity_practicalno191.xml
<Button
android:id="@+id/refreshButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="refresh products"
android:textColor="@color/white" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/refreshButton">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:textColor="@color/black"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
MyService.java
package com.hdm.harshalmakodepractical;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.faded);
myPlayer.setLooping(false);
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
}
Practicalno20.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class practicalno20 extends AppCompatActivity {
Button buttonStart, buttonStop,buttonNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno20);
buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonNext = findViewById(R.id.buttonNext);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(new Intent(practicalno20.this, MyService.class));
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(new Intent(practicalno20.this, MyService.class));
}
});
buttonNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(practicalno20.this,practicalno20_1.class);
startActivity(intent);
}
});
}
}
activity_practicalno20.xml
<Button
android:id="@+id/buttonStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Start Service" />
<Button
android:id="@+id/buttonStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/buttonStart"
android:text="Stop Service" />
<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:text="Next Page" />
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
Practicalno21.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno21);
}
@Override
protected void onDestroy() {
unregisterReceiver(myReceiver);
super.onDestroy();
}
activity_practicalno21.xml
<Button
android:id="@+id/broadcastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Broadcast Intent"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
Most of the android devices have built-in sensors that measure motion, orientation,
and various environmental condition. Android allows us to get the raw data from these
sensors and use it in our application.
The android platform supports three broad categories of sensors. Motion Sensors,
Environmental sensors, Position sensors. Some of the sensors are hardware based and
some are software-based sensors. Whatever the sensor is, android allows us to get the
raw data from these sensors and use it in our application. For this, android provides us
with some classes. Android provides Sensor Manager and Sensor classes to use the
sensors in our application. In order to use sensors, first thing you need to do is to
instantiate the object of SensorManager class.
Example: SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below:
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared, you need to register its listener and override two methods
which are onAccuracyChanged and onSensorChanged. Its syntax is as follows:
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) { }
Methods:
1. getDefaultSensor(int type) :- This method get the default sensor for a given type.
Explain methods
2. getOrientation(float[] R, float[] values) :- This method returns a description of the
current primary clip on the clipboard but not a copy of its data.
3. getInclination(float[] I) :- This method computes the geomagnetic inclination angle
in radians from the inclination matrix.
4. registerListener(SensorListener listener, int sensors, int rate) :-This method registers
a listener for the sensor.
5. unregisterListener(SensorEventListener listener, Sensor sensor) :-This method
unregisters a listener for the sensors with which it is registered.
6. getOrientation(float[] R, float[] values) :-This method computes the device's
orientation based on the rotation matrix.
7. getAltitude(float p0, float p) :-This method computes the Altitude in meters from
the atmospheric pressure and the pressure at sea-level.
Practicalno22.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
layout = findViewById(R.id.layout);
sensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
accelerometer =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorListTextView.setText(sensorList.toString());
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
@Override
public void onAccuracyChanged(Sensor sensor, int i) { }
activity_practicalno22.xml
<TextView
android:id="@+id/sensorListTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sensor List:"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
IV. Output
V. Marks Obtained
I. Theory:
The Android framework includes support for various cameras and camera features
available on devices, allowing you to capture pictures and videos in your application.
Camera can be used in your application in following ways.
1. Using existing android camera application in our application
2. Directly using Camera API provided by android in our application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera
application installed on your phone. Its syntax is given below:
Intent intent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
We will be using the camera API to integrate the camera in our application. First you
will need to initialize the camera object using the static method provided by the api
called Camera. Open. Its syntax is:
Camera object = null;
object = Camera.open();
Methods:
1. startActivityForResult(Intent intent, int requestCode, Bundle options) It starts an
activity, but can take extra bundle of options withit.
2. startActivityFromChild(Activity child, Intent intent, int requestCode) It launchesthe
activity when your activity is child of any otheractivity.
3. startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle
options) It work same as above, but it can take extra values in the shape of bundle
with it.
4. startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)It
launches activity from the fragment you are currentlyinside.
5. startActivityFromFragment(Fragment fragment, Intent intent, intrequestCode,
Bundle options) It not only launches the activity from the fragment, but can take extra
values withit.
Practicalno23.java
package com.hdm.harshalmakodepractical;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.Manifest;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno23);
imageView = findViewById(R.id.imageView);
captureImageButton = findViewById(R.id.captureImageButton);
captureVideoButton = findViewById(R.id.captureVideoButton);
videoView = findViewById(R.id.videoView);
captureVideoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakeVideoIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
// Display the captured image in the ImageView
if (data != null && data.getExtras() != null) {
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
if (imageBitmap != null) {
imageView.setImageBitmap(imageBitmap);
} else {
Toast.makeText(this, "Error capturing image",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No data received from camera",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_VIDEO_CAPTURE) {
Uri videoUri = data.getData();
if (videoUri != null) {
// Display the captured video in the VideoView
videoView.setVideoURI(videoUri);
videoView.start();
} else {
Toast.makeText(this, "Error capturing video",
Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
setupCaptureButtonListeners();
} else {
Toast.makeText(this, "Camera permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
activity_practicalno23.xml
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:src="@android:drawable/ic_menu_camera" />
<Button
android:id="@+id/captureImageButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:text="Capture Image" />
<Button
android:id="@+id/captureVideoButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:text="Capture Video" />
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"/>
</LinearLayout>
AndriodManifest.xml
<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.HarshalMakodePractical"
tools:targetApi="31">
<activity
android:name=".Practicalno23"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</application>
</manifest>
IV. Output
V. Marks Obtained
I. Theory:
Bluetooth is a way to send or receive data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to
wirelessly exchange data with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
1. Scan for other Bluetooth devices
2. Get a list of paired devices.
3. Connect to other devices through service discovery.
Android provides Bluetooth Adapter class to communicate with Bluetooth. Create an
object of this calling by calling the static method getDefaultAdapter(). Its syntax is
given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following
Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Once you enable the Bluetooth, you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of Bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Practicalno24.java
package com.hdm.harshalmakodepractical;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.util.Set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno24);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth is not supported on this
device", Toast.LENGTH_LONG).show();
finish();
}
getVisibleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
makeDeviceVisible();
}
});
Button turnOnBtn = findViewById(R.id.btnTurnOn);
Button turnOffBtn = findViewById(R.id.btnTurnOff);
Button listDevicesBtn = findViewById(R.id.btnListDevices);
deviceListView = findViewById(R.id.deviceListView);
enableBluetooth();
turnOnBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
enableBluetooth();
}
});
turnOffBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
disableBluetooth();
}
});
listDevicesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listPairedDevices();
}
});
}
if
(checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(new
String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 1);
} else {
if (bluetoothAdapter != null) {
Intent enableBluetoothIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, 1);
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is not supported on
this device", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already turned on",
Toast.LENGTH_SHORT).show();
}
}
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
adapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
adapter.add("No paired devices found");
}
deviceListView.setAdapter(adapter);
}
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATI
ON, 300);
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_ADVERTISE) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(discoverableIntent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
activity_practicalno24.xml
<Button
android:id="@+id/btnTurnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On Bluetooth"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/btnTurnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off Bluetooth"
android:layout_below="@id/btnTurnOn"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/btnListDevices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Paired Devices"
android:layout_below="@id/btnTurnOff"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/btnGetVisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Visible"
android:layout_below="@id/btnListDevices"
android:layout_centerHorizontal="true"/>
<ListView
android:id="@+id/deviceListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnGetVisible"/>
</RelativeLayout>
AndriodManifest.xml
<uses-feature android:name="android.hardware.bluetooth"
android:required="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADVERTISE" />
<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.HarshalMakodePractical"
tools:targetApi="31">
<activity
android:name=".Practicalno24"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</application>
</manifest>
IV. Output
V. Marks Obtained
I. Theory:
Animation is the process of creating motion and shape change. Tween Animation
takes some parameters such as start value, end value, size, time duration, rotation
angle etc., and perform the required animation on that object. It can be applied to any
type of object.
In order to perform animation in android, we are going to call a static function
loadAnimation() of the class AnimationUtils. We are going to receive the result in an
instance of Animation Object. Its syntax is as follows:
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
In order to apply this animation to an object, we will just call the startAnimation()
method of the object. Its syntax is:
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
Methods:
1. start(): This method starts the animation.
2. setDuration(long duration) :This method sets the duration of an animation.
3. getDuration() : This method gets the duration which is set by above method.
4. end() : This method ends the animation.
5. cancel() : This method cancels the animation.
Practicalno25.java
package com.hdm.harshalmakodepractical;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno25);
imageView1 = findViewById(R.id.imageView1);
buttonRotate.setOnClickListener(new View.OnClickListener() {
@Override
buttonZoom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView1.startAnimation(zoomAnimation);
}
});
buttonFade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView1.startAnimation(fadeInOutAnimation);
}
});
}
// Optional: You can define these methods if you set onClick in XML
public void onRotateButtonClick(View view) {
imageView1.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.rotate));
}
imageView1.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoom));
}
imageView1.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in_out));
}
}
activity_practicalno25.xml
<ImageView
android:id="@+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@android:drawable/ic_dialog_alert"
android:layout_centerInParent="true"
android:scaleType="fitXY" />
<Button
android:id="@+id/buttonRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate"
android:layout_below="@id/imageView1"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"
android:onClick="onRotateButtonClick" />
<Button
android:id="@+id/buttonZoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Zoom"
android:layout_below="@id/buttonRotate"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"
android:onClick="onZoomButtonClick" />
<Button
android:id="@+id/buttonFade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade"
android:layout_below="@id/buttonZoom"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"
android:onClick="onFadeButtonClick" />
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
Practicalno26.java
package com.hdm.harshalmakodepractical;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno26);
etName = findViewById(R.id.etName);
etAge = findViewById(R.id.etAge);
btnInsert = findViewById(R.id.btnInsert);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = etName.getText().toString();
String ageString = etAge.getText().toString();
if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(practicalno26.this, "Please enter name and age",
Toast.LENGTH_SHORT).show();
return;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(practicalno26.this, "Data inserted successfully",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " TEXT," +
COLUMN_AGE + " INTEGER);");
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
activity_practicalno26.xml
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"/>
<EditText
android:id="@+id/etAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/etName"
android:layout_marginTop="8dp"
android:inputType="number"
android:hint="Enter Age"/>
<Button
android:id="@+id/btnInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/etAge"
android:layout_marginTop="16dp"
android:text="Insert Data"/>
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
This day Login and Registration form in Android are part of every application. So,
when we are programming, we work with many registration forms. Forms can be very
different from a simple login or registration to a complex ordering form for any
application.
A login application is the screen asking your credentials to login to some particular
application. You might have seen it when logging into Facebook, twitter etc. First you
have to define two Text View asking username and password of the user.
Define a button with login text.
In the java file, inside the method of onClick get the username and passwords text
using getText() and toString() method and match it with the text using equals()
function.
The last thing you need to do is to provide a security mechanism, so that unwanted
attempts should be avoided. For this initialize a variable and on each false attempt,
decrement it. And when it reaches to 0, disable the login button.
Practicalno27.java
package com.hdm.harshalmakodepractical;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno27);
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
buttonLogin = findViewById(R.id.buttonLogin);
textViewAttempts = findViewById(R.id.textViewAttempts);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
if (isValidCredentials(username, password)) {
showLoginSuccess();
} else {
loginAttempts--;
if (loginAttempts <= 0) {
buttonLogin.setEnabled(false);
showLoginFailure("Login disabled. Too many failed attempts.");
} else {
showLoginFailure("Invalid username or password. Try again.");
}
}
}
});
}
activity_practicalno27.xml
<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:layout_marginTop="16dp"/>
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewUsername"
android:layout_marginTop="8dp"
android:inputType="text"/>
<TextView
android:id="@+id/textViewPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_below="@id/editTextUsername"
android:layout_marginTop="16dp"/>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewPassword"
android:layout_marginTop="8dp"
android:inputType="textPassword"/>
<TextView
android:id="@+id/textViewAttempts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts remaining: 3"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"/>
<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/textViewAttempts"
android:layout_marginTop="16dp"/>
</RelativeLayout>
IV. Output
V. Marks Obtained
Practical No. 28: Create login application where you will have to
validate username and password till the username and password is
not validated, login button should remain disabled.
I. Theory:
This day Login and Registration form in Android are part of every application out
there. So, when we are programming, we work with many registration forms. Forms
can be very different from a simple login or registration to a complex ordering form
for any application.
With registration, how you can check data that the user has entered with simple
validation. Validation can check many conditions. We can verify if an email address is
a valid email and if a user entered all the required data, for instance, we check if Edit
Text is empty for the first and last name. We can prepare a way to notify the user that
the data is not valid. On login activity, we should check for password length. There are
a few things login and registration form need:
• Clean user interface.
• Validation (check if the email is an email and if the user entered all the data).
• Notifications for the user that the data is incorrect.
• Instructions for the user (e.g. how many characters are required for password).
Practicalno28.java
package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno28);
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
buttonLogin = findViewById(R.id.buttonLogin);
textViewAttempts = findViewById(R.id.textViewAttempts);
buttonLogin.setEnabled(false);
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
@Override
public void afterTextChanged(Editable s) {
}
};
editTextUsername.addTextChangedListener(textWatcher);
editTextPassword.addTextChangedListener(textWatcher);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
if (isValidCredentials(username, password)) {
showLoginSuccess();
} else {
loginAttempts--;
textViewAttempts.setText("Attempts remaining: " + loginAttempts);
if (loginAttempts <= 0) {
buttonLogin.setEnabled(false);
showLoginFailure("Login disabled. Too many failed attempts.");
} else {
showLoginFailure("Invalid username or password. Try again.");
}
}
}
});
}
activity_practicalno28.xml
<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:layout_marginTop="16dp"/>
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewUsername"
android:layout_marginTop="8dp"
android:inputType="text"/>
<TextView
android:id="@+id/textViewPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_below="@id/editTextUsername"
android:layout_marginTop="16dp"/>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewPassword"
android:layout_marginTop="8dp"
android:inputType="textPassword"/>
<TextView
android:id="@+id/textViewAttempts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts remaining: 3"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"/>
<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/textViewAttempts"
android:layout_marginTop="16dp"
android:enabled="false"/>
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
Android devices can send and receive messages to or from any other phone that
supports Short Message Service (SMS). Android offers the Messenger application that
can send and receive SMS messages.
A host of third-party apps for sending and receiving SMS messages are also available
in Google Play. The SMS protocol was primarily designed for user-to-user
communication and is not well-suited for apps that want to transfer data. You should
not use SMS to send data messages from a web server to your app on a user device.
SMS is neither encrypted nor strongly authenticated on either the network or the
device
Access to the SMS features of an Android device is protected by user permissions.
Just as your app needs the user's permission to use phone features, so also does an app
need the user's permission to directly use SMS features.
You have two choices for sending SMS messages:
• Use an implicit Intent to launch a messaging app such as Messenger, with the
ACTION_SENDTOaction.
• Send the SMS message using the sendTextMessage() method or other methods of the
SmsManagerclass.
To receive SMS messages, the best practice is to use the onReceive() method of the
Broadcast Receiver class. The Android framework sends out system broadcasts of
events such as receiving an SMS message, containing intents that are meant to be
received using a Broadcast Receiver. Your app receives SMS messages by listening
for the SMS_RECEIVED_ACTION broadcast.
Methods :
1 ArrayList<String> divideMessage(String text) :-This method divides a message text
into several fragments, none bigger than the maximum SMS message size.
2 static SmsManager getDefault() :- This method is used to get the default instance of
the Sms Manager
3 void sendDataMessage(String destination Address, String scAddress, short
destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent):-
This method is used to send a data based SMS to a specific application port.
4 void sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent) :-Send a text based SMS.
Practicalno29.java
package com.hdm.harshalmakodepractical;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
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;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno29);
editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSend = findViewById(R.id.buttonSend);
textView = findViewById(R.id.textView);
registerReceiver(smsReceiver, new
IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phoneNumber = editTextPhoneNumber.getText().toString();
String message = editTextMessage.getText().toString();
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
} else {
return true;
}
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_SMS_PERMISSION) {
// Check if the permission is granted
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, proceed with sending SMS
String phoneNumber = editTextPhoneNumber.getText().toString();
String message = editTextMessage.getText().toString();
sendSMS(phoneNumber, message);
} else {
// Permission denied, show a message or handle accordingly
Toast.makeText(this, "SMS permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])
pdu);
String senderPhoneNumber = smsMessage.getOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
displayReceivedSMS(senderPhoneNumber, messageBody);
}
}
}
}
};
activity_practicalno29.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Received SMS will be displayed here." />
<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_marginTop="16dp"
android:hint="Enter phone number"/>
<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhoneNumber"
android:layout_marginTop="8dp"
android:hint="Enter message"/>
<Button
android:id="@+id/buttonSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_below="@id/editTextMessage"
android:layout_marginTop="16dp"/>
</RelativeLayout>
AndroidManifest.xml
SmsReceiver.java
package com.hdm.harshalmakodepractical;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String senderPhoneNumber = smsMessage.getOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
displayReceivedSMS(context, senderPhoneNumber, messageBody);
}
}
}
}
IV. Output
V. Marks Obtained
I. Theory:
To send email from your Android application, you have to write an Activity that needs
to launch an email client and sends an email using your Android device. This practical
focuses on integrating the existing email clients in the new applications.
Intent Object - Action to send Email:
You will use ACTION_SEND action to launch an email client installed on your
Android device. Following is simple syntax to create an intent with ACTION_SEND
action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Intent Object – Data Type to send Email
To send an email you need to specify mailto: as URI using setData() method and data
type will be to text/plain using setType() method as follows:
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
Practicalno30.java
package com.hdm.harshalmakodepractical;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno30);
recipientEditText = findViewById(R.id.editRecipient);
subjectEditText = findViewById(R.id.editSubject);
bodyEditText = findViewById(R.id.editBody);
}
// Verify that the device has an email client to handle this intent
if (emailIntent.resolveActivity(getPackageManager()) != null) {
// Start the email client
startActivity(emailIntent);
}
}
}
activity_practicalno30.xml
<EditText
android:id="@+id/editRecipient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Recipient Email" />
<EditText
android:id="@+id/editSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editRecipient"
android:layout_marginTop="16dp"
android:hint="Email Subject" />
<EditText
android:id="@+id/editBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editSubject"
android:layout_marginTop="16dp"
android:hint="Email Body" />
<Button
android:id="@+id/btnSendEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editBody"
android:layout_marginTop="16dp"
android:text="Send Email"
android:onClick="sendEmail" />
</RelativeLayout>
IV. Output
V. Marks Obtained
I. Theory:
Android allows us to integrate google maps in our application. You can show any
location on the map, or can show different routes on the map. You can also customize
the map according to your choices.
Add the map fragment into xml layout file. Its syntax is given below –
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Add some permissions along with the Google Map
API key in the AndroidManifest.XML file. Its syntax is given below:
<!--Permissions-->
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STO
RAGE" />
Practicalno31.java
package com.hdm.harshalmakodepractical;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno31);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
LatLng Warora = new LatLng(20.246368, 79.023188);
mMap.addMarker(new MarkerOptions().position(Warora).title("Marker in
Warora"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(Warora,13
),4000,null);
}
}
activity_practicalno31.xml
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
AndroidManifest.xml
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/><uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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.HarshalMakodePractical"
tools:targetApi="28">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAxF2PlYeU8Bry0pk1vdC0Tu7KTeLjxj0U" />
<activity
android:name=".practicalno31"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
build.gradle
dependencies {
implementation 'com.google.android.gms:play-services-maps:18.0.2'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
IV. Output
V. Marks Obtained
I. Theory:
Android allows us to integrate google maps in our application. You can show any
location on the map, or can show different routes on the map. You can also customize
the map according to your choices.
Methods available in the Google Map class are given below.
1. addCircle(CircleOptions options) : This method add a circle to the map
2. addPolygon(PolygonOptions options) : This method add a polygon to the map
3. addTileOverlay(TileOverlayOptions options) : This method add tile overlay to the
map
4. animateCamera(CameraUpdate update) : This method Moves the map according to
the update with an animation
5. clear() : This method removes everything from the map
6. getMyLocation() : This method returns the currently displayed user location
7. moveCamera(CameraUpdate update) : This method repositions the camera
according to the instructions defined in the update
8. setTrafficEnabled(boolean enabled) : This method Toggles the traffic layer on or off
9. snapshot(GoogleMap.SnapshotReadyCallback callback) : This method Takes a
snapshot of the map
10. stopAnimation() : This method stops the camera animation if there is one in
progress
Practicalno32.java
package com.hdm.harshalmakodepractical;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
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.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno32);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
LatLng warora = new LatLng(20.246368, 79.023188);
mMap.addMarker(new MarkerOptions().position(warora).title("Marker in
Warora"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(warora, 13),
4000, null);
LatLng origin = new LatLng(20.246368, 79.023188);
LatLng destination = new LatLng(20.994957, 78.204946);
drawRoute(mMap, origin, destination);
mMap.addCircle(new CircleOptions()
.center(warora).fillColor(Color.parseColor("#9F6FFF76")).strokeColor(Color.GREEN
).radius(300)
);
}
activity_practicalno32.xml
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.9"/>
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thank You"
android:onClick="next"
android:layout_gravity="center"/>
</LinearLayout>
AndroidManifest.xml
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/><uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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.HarshalMakodePractical"
tools:targetApi="28">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAxF2PlYeU8Bry0pk1vdC0Tu7KTeLjxj0U" />
<activity
android:name=".practicalno32"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
build.gradle
dependencies {
implementation 'com.google.android.gms:play-services-maps:18.0.2'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
IV. Output
V. Marks Obtained