You are on page 1of 153

Government College of Engineering, Karad AST Lab II

Experiment No 1
Title: - Installation of Android SDK, emulator, creating simple project and study of android
project structure.

Outcome:- Students will be able to create simple Android project in SDK.

Theory:-

1. Introduction

Android is an Operating System for mobile devices developed by Google, which is


built upon Linux kernel. Android competes with Apple's iOS (for iPhone/iPad), RIM's
Blackberry, Microsoft's Windows Phone, Symbian OS, and many other proprietary mobile
OSes.

The latest Android 7 (Nougat) supports Phone/Tablet, TV, Wear (watch and glass),
Automobile and Internet of things.

Android Platform

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.

Fig 1 : Android Platform

Department of Information Technology 1


Government College of Engineering, Karad AST Lab II

2. Installing "Android SDK" and "Android Studio IDE"

We need to install both the "Android Studio", which is an IDE based on IntelliJ (a
popular Java IDE); and "Android SDK" libraries.

Step 0: Pre-Installation Check List

Before installing Android SDK, you need to install Java Development Kit (JDK). Read "How
to install JDK". Ensure that your JDK is at or above 1.7. You can check your JDK version
with command "javac -version".

Step 1: Install "Android Studio IDE" and "Android SDK"


(For Windows)
1. Check that environment variable JAVA_HOME is set to the JDK installation
directory via command "set JAVA_HOME". Otherwise, set the JAVA_HOME via
"Control Panel". Check the detail steps HERE.
2. Check the system requirements for Android Studio/SDK @
https://developer.android.com/sdk/index.html#Requirements.
3. Goto "Android Developer" @ https://developer.android.com/index.html ⇒ Select
"Get Android Studio" ⇒ "Download Android Studio For Windows", e.g., android-
studio-bundle-162.xxxxxx-windows.exe, which is a huge file of 1.8GB.
4. Run the downloaded installer. Follow the on-screen instruction and accept the defaults
to complete the installation. You need about 5GB of free disk space! Take note on the
installation locations of "Android Studio" and "Android SDK".
Take note that "Android Studio IDE" is installed in "C:\Program
Files\Android\Android Studio" and "Android SDK" is installed in "C:\Users\your-
username\AppData\Local\Android\sdk".
(For Mac OS X)
1. Check the system requirements @
https://developer.android.com/sdk/index.html#Requirements.
2. Goto "Android Developer" @ https://developer.android.com/index.html ⇒ Select
"Get Android Studio" ⇒ "Download Android Studio For Mac". E.g., android-studio-
ide-162.xxxxxx-mac.dmg (424MB).
3. Launch the downloaded .dmg installation file.
4. Drag and drop Android Studio into the "Applications" folder.

Note: If you see a warning that says the package is damaged and should be moved to the
trash, go to System Preferences ⇒ Security & Privacy ⇒ under Allow applications
downloaded from ⇒ select Anywhere. Then run again.

The Android SDK is installed in "~/Library/Android/sdk/".

Step 2: Post-Installation - Adding More SDK Packages

The installation installed basic SDK packages. You may need to add a few more to
run the Hello-world.

Department of Information Technology 2


Government College of Engineering, Karad AST Lab II

Adding too many SDK packages, especially the so-called system images for emulating
different device (e.g., various phone/tablet), will take an extremely LONG time, especially if
everyone is downloading and jamming up the network. The system images also take up a lot
of disk space - more than 10 GB per API level!!! For our toy project, we only need a small
set of SDK packages.

[TODO] Check if it is possible to copy the SDK instead of downloading during installation?

(For Windows)

[March 2017] DO NOTHING! In this latest Android Studio, all the necessary components
have been installed.

1. Launch Android Studio ⇒ Check "I do not have previous version of Android Studio"
⇒ Android studio setup wizard will download more SDK components ⇒ Wait for it
to complete ⇒ Finish.
2. Select "Configure" ⇒ "SDK Manager" ⇒ Select "SDK Tools" tab ⇒ Check "Android
Support Repository/Library", "Intel x86 Emulator Accelerator (HAXM Installer)" and
"Google USB Driver" ⇒ Apply.

(For Mac OS X)

1. Launch Android Studio (from Applications) ⇒ Android studio setup wizard will
download more SDK components ⇒ Wait and wait and wait for it to complete ⇒
Finish. (If error occurs in installing "platform-tools" ⇒ Cancel.)
2. Select "Configure" ⇒ "SDK Manager" ⇒ If error "Please specify an Android SDK
Location" occurs, click "Edit" and COPY the SDK location
"/Users/.../Library/Android/sdk", then select "Configure" ⇒ Project defaults ⇒
Project structure ⇒ In "Android SDK Location", PASTE it.
3. Select "Configure" ⇒ "SDK Manager" ⇒ "Launch Standalone SDK Manager" ⇒
Click "Deselect All" (otherwise, it will take hours to install all the packages) ⇒ Check
that these packages are "installed"; otherwise, check them to install:
 Under "Tools":
a) "Android SDK Tools"
b) "Android SDK Platform-tools"
c) "Android SDK Build-tools (highest version)"
 Under "Android 7.0 (API 25)" (or the latest version):
a) "SDK Platform"
b) At least one "System Image". If any of the "xxxxxx System Images" is already
installed, okay. Otherwise, check "Google APIs" and "Google APIs Intel x86 Atom
System Image" (which seems to be the fastest among a few I tried).

[Notes: (1) System Image is huge (>1GB each). (2) Android devices could be built on many
different hardware processors, e.g., Intel x86, ARMv5, and ARMv7. Android SDK provides
"emulator" for you to test your app on ALL hardware, by building a System-Image for EACH

Department of Information Technology 3


Government College of Engineering, Karad AST Lab II

of the hardware. Our toy project does not need to be simulated on ALL hardware but just
anyone of the hardware!]

 Under "Extras":
a) "Android Support Repository/Library"
b) "Google Repository"
c) "Intel x86 Emulator Accelerator (HAXM Installer)"

Click "Install n packages". This step is SLOW! very SLOW! The SDK will be installed under
"~/Library/Android/sdk" for Mac OS X.

3. Write your First Android App

Android apps are written in Java, and use XML extensively. I shall assume that you have
basic knowledge of Java and XML.

Take note that Android emulator is slow - VERY VERY VERY SLOW!!! Be Patient!!!

3.1 Hello-World

Step 0: Read

Goto "Android Training" @ https://developer.android.com/training/index.html. Read "Get


Started" and "Building your first app".

Step 1: Create a New Android Project

1) Launch Android Studio.


2) Choose "Start a new Android Studio Project".
3) In "New Project: Configure your new project" dialog ⇒ Set "Application Name" to
"Hello Android" (this will be the title in your app menu) ⇒ Set your "Company
Domain" to "example.com" ⇒ In "Project Location", choose your project directory,
e.g., d:\myProject or use the default location ⇒ Leave the rest to their default values
⇒ Next.
4) In "Installing Requested Components" ⇒ Next.
5) In "Target Android Devices: Select the form factor your app will run on" ⇒ Check
"Phone and Tablet" ⇒ In "Minimum SDK", choose "API 15: Android 4.0.3
(IceCreamSandwich)" ⇒ Leave all of the other options (TV, Wear, and Glass)
unchecked ⇒ Next.
6) In "Add an activity to Mobile" dialog ⇒ Select "Empty Activity" (default) ⇒ Next.
7) In "Customize the Activity" dialog ⇒ Set "Activity Name" to "MainActivity"
(default) ⇒ Set "Layout Name" to "activity_main" (default) ⇒ Finish.
8) Be patient! It could take a while to set up your first app. The app appears after
"Indexing..." (at the bottom status bar) completes. By default, a hello-world app is
created.

Department of Information Technology 4


Government College of Engineering, Karad AST Lab II

Fig 2 - Create a New Android Project

Step 2: Setup Emulator (aka Android Virtual Device (AVD))

To run your Android app under the emulator, you need to first create an Android
Virtual Devices (AVD). An AVD models a specific device (e.g., your jPone or Taimi). You
can create AVDs to emulate different android devices (e.g., phone/tablet, android version,
screen size, and etc.).

1) In Android studio, select "Tools" ⇒ Android ⇒ AVD Manager.


2) Click "Create Virtual Device".
3) In "Select Hardware: Choose a device definition" dialog ⇒ In "Category", choose
"Phone" ⇒ In "Name", choose "2.7 QVGA" (the smallest device available - you can
try a bigger device later) ⇒ Next.
4) In "System Image" ⇒ Next.
5) In "AVD Name", enter "QVGA" ⇒ Finish.

Step 3: Run the Android App on Emulator

1) Select the "Run" menu ⇒ "Run app" ⇒ Check "Launch Emulator" ⇒ Select "QVGA"
⇒ OK.
2) You MAY BE prompted to install Intel HAXM (Hardware Accerlerated Execution
Manager). Follow the instruction to install HAXM.
3) You MAY BE asked to enable VT-x in BIOS. Reboot your computer, hit a hot-key to
enter BIOS (ESC for my HP). Enable VT-x under "Advanced" ⇒ "System Options"
(could be different for different computer). See below "Problem and Error Notes".
4) Be patient! It may take a few MINUTES to fire up the app on the emulator. You first
see a black screen ⇒ then the word "Android" ⇒ then the wallpaper ⇒ then the
"Hello, world!" message.
5) If you have problem running on the emulator, I suggest you try to run on an actual
Android device (phone/pad) if you have one. Goto next step.

Department of Information Technology 5


Government College of Engineering, Karad AST Lab II

6) DO NOT CLOSE THE EMULATOR, as it really takes a long time to start. You could
always re-run the app (or run a new app) on the same emulator. Try re-run the app by
selecting "Run" menu ⇒ "Run app" ⇒ Now, "QVGA" should appear under "Choose a
running device" (as it has already started) ⇒ Select it ⇒ OK.

Project Folder Structures

Folder structure in the newly created project in Project mode would look like below.

Fig 3 - Project Folder Structures

Different folders and files are as below –

HelloWorld: This is project root directory.

.gradle: In this folder, you can find all the settings and files used by gradle to build the
project. You can delete these files if you want. These files will be created when you will
build the project again.

.idea: Android Studio stores project specific meta-data in this folder. It contains a set of
configuration files. Each file contains configuration data for a certain functional area. The
name of the file explain the functional area itself. For example, compiler.xml, encodings.xml,
modules.xml file etc.

app: This is actual project folder where code related to project is stored. Here, you write
code, create UI, stores assets etc. We will discuss about this section in detail soon.

build: This folder contains build related data. Data is generated when you build the project.

Department of Information Technology 6


Government College of Engineering, Karad AST Lab II

gradle: You would notice that there is wrapper folder inside this. When you distribute the
wrapper with your project, anyone can work on the project without installing the Gradle.
Another advantage is other users are guaranteed to use same version of Gradle that build was
designed to work properly.

.gitignore: We include all the files in this folder that we want to exclude from version control
system.

buld.gradle: This is a top-level build file where we add configuration options common to all
sub-projects/modules. This is different from app/build.gradle file.

gradle.properties: This is where you configure project-wide Gradle settings. For example,
Gradle daemon’s maximum heap size etc.

gradlew: This file is related to gradle. It is created once and updated when a new feature or
plugin is required that needs updated gradle version.

gradlew.bat: This file is related to gradle. It is created once and updated when a new feature
or plugin is required that needs updated gradle version.

HelloWorld.iml: This is a module file created by IntelliJ IDEA, an IDE used to develop Java
applications. It stores information about a development module, which may be a Java, Plugin,
Android, or Maven component; saves the module paths, dependencies, and other settings.

local.properties: It contains information specific to your local configuration. For example,


path to SDK etc. Since it contains local information, it should not be checked into version
control system.

settings.gradle: This file handles project, module and other kinds of names and settings,

External Libraries: This is not actually a folder but a place where referenced libraries are
shown.
App Section Structures
App section looks like below.

Fig 4 - App Section Structures

Department of Information Technology 7


Government College of Engineering, Karad AST Lab II

app folder has following files and sub-folders.


app/build: This contains output generated when we run the application. i.e. It contains build
outputs.
app/libs: It contains libraries being used with this app module.
app/src: It contains all code and resource files(images, audio, video etc.) that are needed in
the app module. It has sub folders too. We will discuss, in detail, about this later.
app/.gitignore: We include all the files(present in the app module) that we do not want to
check into version control system.
app/app.iml: IML is a module file created by IntelliJ IDEA, an IDE used to develop Java
applications. It stores information about a development module, which may be a Java plugin,
Android, or Maven component, saves the module paths, dependencies, and other settings.
app/build.gradle: This file contains build configurations specific to this app module.
app/proguard-rules.pro: This is where we add custom ProGuard rules. ProGuard detects
and removes unused classes, fields, methods and attributes from your packaged app,
including those from included code libraries. It also optimises the byte code, removed unused
code instructions, and obfuscates the remaining classes, fields, and methods with short
names. The obfuscated code make the APK difficult to reverse engineer, which is extremely
valuable, especially when we have payment related information.
Now, coming to the app/src sections.
App/src Section Structures
This section contains source code and all resources that we need to build any application.
Below image shows the structure.

Fig 5 - App/src Section Structures

Department of Information Technology 8


Government College of Engineering, Karad AST Lab II

It has three sub-folders – androidTest, main and test.


androidTest: We write code into this folder to perform unit testing that need android device
or emulator. These tests will have access to instrumentation information. For example,
context of the app you are testing. So, write code into this folder to test the code that use
Android framework. Moreover, Use this folder when your tests have android dependencies
that mock objects can not satisfy.
main: This contains the main source-code(Android code and resource files), that we need to
build project. We will talk about this later.
test: We write code into this folder to perform unit testing that do not need android device or
emulator. These tests run locally on the Java Virtual Machine(JVM). Use these test to
minimize execution time when tests have no Android framework dependencies or when you
can mock android framework dependencies.
Now, coming to the main folder.

App/src/main Section Structures

This folder contains the actual android code and resource files. Below image clearly depicts
the folder structure.

Fig 6 - App/src/main Section Structures

This folder contains following files and sub-folders.

Department of Information Technology 9


Government College of Engineering, Karad AST Lab II

AndroidManifest.xml: You must have this file in any android application. It describes the
nature of the application and each of its components. it also contains the name of java
package of the application that serves as unique identifier for the application. It also contains
minimum android API level that application requires.
java: This folder contains java code source.
res: It contains application resources, such as drawable files, layout files, and UI string,
dimension, colors etc. This folder also has sub-folders as below. Below are the sub-folder that
resides inside res folder –
res/drawable: This folder contains drawable xml files and images.
res/mipmap: This folder contains launcher icon.
res/values: In values folder, we store different values used in the application. For example,
different colours, dimensions, strings, styles used in the application. They are basically used
to remove hardcoded value in the application. This also helps in resource localisation and
internationalisation.
This folder contains a separate file for each type of values. They are –
res/values/colors.xml: This file contains different colors used in the application.
res/values/dimens.xml: This file contains different dimension used in the application.
res/values/strings.xml: This file contains different strings used in the application.
res/values/styles.xml: This file contains different styles used in the application.
Other folder in res folder
res/raw: You can create this folder in res folder and store audio, video etc. into it.

Conclusion: Thus, I have Installation of Android SDK, emulator, creating simple project and
study of android project structure.

Department of Information Technology 10


Government College of Engineering, Karad AST Lab II

Experiment No 2
Title: - Write a program to demonstrate Buttons, Text Fields, Checkboxes, Radio Buttons,
and Toggle Buttons with their events handler.

Outcome: - Students will be able to implement Buttons, Text Fields, Checkboxes, Radio
Buttons, and Toggle Buttons with their events handler.

Theory:-

Buttons:-
A button consists of text or an icon (or both text and an icon) that communicates what action
occurs when the user touches it.

Fig 1: Buttons
Depending on whether you want a button with text, an icon, or both, you can create the
button in your layout in three ways:

 With text, using the Button class:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
... />

 With an icon, using the ImageButton class:

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_icon"
... />

 With text and an icon, using the Button class with the android:drawableLeft attribute:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:drawableLeft="@drawable/button_icon"
... />

Department of Information Technology 11


Government College of Engineering, Karad AST Lab II

 Responding to Click Events

When the user clicks a button, the Button object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to
the <Button> element in your XML layout. The value for this attribute must be the name of
the method you want to call in response to a click event. The Activity hosting the layout must
then implement the corresponding method.

For example, here's a layout with a button using android:onClick:

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


<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />

Within the Activity that hosts this layout, the following method handles the click event:

/** Called when the user touches the button */


public void sendMessage(View view) {
// Do something in response to button click
}

The method you declare in the android:onClick attribute must have a signature exactly as
shown above. Specifically, the method must:

 Be public

 Return void

 Define a View as its only parameter (this will be the View that was clicked)

 Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout.
This might be necessary if you instantiate the Button at runtime or you need to declare the
click behavior in a Fragment subclass.

To declare the event handler programmatically, create an View.OnClickListener object and


assign it to the button by callingsetOnClickListener(View.OnClickListener). For example:

Department of Information Technology 12


Government College of Engineering, Karad AST Lab II

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


button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});

 Styling Your Button

The appearance of your button (background image and font) may vary from one device to
another, because devices by different manufacturers often have different default styles for
input controls.

You can control exactly how your controls are styled using a theme that you apply to your
entire application. For instance, to ensure that all devices running Android 4.0 and higher use
the Holo theme in your app, declare android:theme="@android:style/Theme.Holo" in your
manifest's <application>element. Also read the blog post, Holo Everywhere for information
about using the Holo theme while supporting older devices.

To customize individual buttons with a different background, specify


the android:background attribute with a drawable or color resource. Alternatively, you can
apply a style for the button, which works in a manner similar to HTML styles to define
multiple style properties such as the background, font, size, and others. For more information
about applying styles.

 Borderless button

One design that can be useful is a "borderless" button. Borderless buttons resemble basic
buttons except that they have no borders or background but still change appearance during
different states, such as when clicked.

To create a borderless button, apply the borderlessButtonStyle style to the button. For
example:

<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
style="?android:attr/borderlessButtonStyle" />

Department of Information Technology 13


Government College of Engineering, Karad AST Lab II

 Custom background

If you want to truly redefine the appearance of your button, you can specify a custom
background. Instead of supplying a simple bitmap or color, however, your background should
be a state list resource that changes appearance depending on the button's current state.

You can define the state list in an XML file that defines three different images or colors to
use for the different button states.

To create a state list drawable for your button background:

1. Create three bitmaps for the button background that represent the default, pressed, and
focused button states.

To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-
patch bitmaps.
2. Place the bitmaps into the res/drawable/ directory of your project. Be sure each bitmap is
named properly to reflect the button state that they each represent, such
as button_default.9.png, button_pressed.9.png, and button_focused.9.png.

3. Create a new XML file in the res/drawable/ directory (name it something


like button_custom.xml). Insert the following XML:

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


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused"
android:state_focused="true" />
<item android:drawable="@drawable/button_default" />
</selector>

This defines a single drawable resource, which will change its image based on the current
state of the button.
o The first <item> defines the bitmap to use when the button is pressed (activated).

o The second <item> defines the bitmap to use when the button is focused (when the
button is highlighted using the trackball or directional pad).

o The third <item> defines the bitmap to use when the button is in the default state (it's
neither pressed nor focused).

This XML file now represents a single drawable resource and when referenced by
a Button for its background, the image displayed will change based on these three states.

Department of Information Technology 14


Government College of Engineering, Karad AST Lab II

4. Then simply apply the drawable XML file as the button background:

<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
android:background="@drawable/button_custom" />

 Radio Buttons
Radio buttons allow the user to select one option from a set. You should use radio buttons for
optional sets that are mutually exclusive if you think that the user needs to see all available
options side-by-side. If it's not necessary to show all options side-by-side, use
a spinner instead.

Fig 2: Radio Buttons


To create each radio button option, create a RadioButton in your layout. However, because
radio buttons are mutually exclusive, you must group them together inside a RadioGroup. By
grouping them together, the system ensures that only one radio button can be selected at a
time.

 Responding to Click Events

When the user selects one of the radio buttons, the corresponding RadioButton object
receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to
the <RadioButton> element in your XML layout. The value for this attribute must be the
name of the method you want to call in response to a click event. The Activity hosting the
layout must then implement the corresponding method.

For example, here are a couple RadioButton objects:

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


<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

Department of Information Technology 15


Government College of Engineering, Karad AST Lab II

<RadioButton android:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="@+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>

Within the Activity that hosts this layout, the following method handles the click event for
both radio buttons:

public void onRadioButtonClicked(View view) {


// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked


switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}

The method you declare in the android:onClick attribute must have a signature exactly as
shown above. Specifically, the method must:

 Be public

 Return void

 Define a View as its only parameter (this will be the View that was clicked)

 Checkboxes
Checkboxes allow the user to select one or more options from a set. Typically, you should
present each checkbox option in a vertical list.

Department of Information Technology 16


Government College of Engineering, Karad AST Lab II

Fig 3: Checkbox
To create each checkbox option, create a CheckBox in your layout. Because a set of
checkbox options allows the user to select multiple items, each checkbox is managed
separately and you must register a click listener for each one.

 Responding to Click Events

When the user selects a checkbox, the CheckBox object receives an on-click event.

To define the click event handler for a checkbox, add the android:onClick attribute to
the <CheckBox> element in your XML layout. The value for this attribute must be the name
of the method you want to call in response to a click event. The Activity hosting the layout
must then implement the corresponding method.

For example, here are a couple CheckBox objects in a list:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_meat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/meat"
android:onClick="onCheckboxClicked"/>
<CheckBox android:id="@+id/checkbox_cheese"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cheese"
android:onClick="onCheckboxClicked"/>
</LinearLayout>

Within the Activity that hosts this layout, the following method handles the click event for
both checkboxes:

Department of Information Technology 17


Government College of Engineering, Karad AST Lab II

public void onCheckboxClicked(View view) {


// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();

// Check which checkbox was clicked


switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
// Put some meat on the sandwich
else
// Remove the meat
break;
case R.id.checkbox_cheese:
if (checked)
// Cheese me
else
// I'm lactose intolerant
break;
// TODO: Veggie sandwich
}
}

The method you declare in the android:onClick attribute must have a signature exactly as
shown above. Specifically, the method must:

 Be public

 Return void
 Define a View as its only parameter (this will be the View that was clicked)

 Toggle Buttons
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 ToggleButton object. Android 4.0
(API level 14) introduces another kind of toggle button called a switch that provides a slider
control, which you can add with a Switch object. SwitchCompat is a version of the Switch
widget which runs on devices back to API 7.

If you need to change a button's state yourself, you can use


the CompoundButton.setChecked() orCompoundButton.toggle() methods.

Fig 4: Toggle Button

Department of Information Technology 18


Government College of Engineering, Karad AST Lab II

Toggle buttons

Fig 5: Toggle Button Switches (in Android 4.0+)


 Responding to Button Presses

To detect when the user activates the button or switch, create


an CompoundButton.OnCheckedChangeListener object and assign it to the button by
callingsetOnCheckedChangeListener(). For example:

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);


toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});

Conclusion :- Thus, I have implemented Buttons, Text Fields, Checkboxes, Radio Buttons,
and Toggle Buttons with their events handler.

Department of Information Technology 19


Government College of Engineering, Karad AST Lab II

Experiment No 3
Title :- Write a program to use of Intents for SMS and Telephony.

Outcome:- Students will be able to implement Intents for SMS and Telephony.

Theory:-
In Android, you can use SmsManager API or devices Built-in SMS application to send
SMS's. In this tutorial, we shows you two basic examples to send SMS message −
 SmsManager API

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
 Built-in SMS application

Intent sendIntent = new Intent(Intent.ACTION_VIEW);


sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Of course, both need SEND_SMS permission.

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


Apart from the above method, there are few other important functions available in
SmsManager class. These methods are listed below −

Sr.No. Method & Description

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 SmsManager

3 void sendDataMessage(String destinationAddress, 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 sendMultipartTextMessage(String destinationAddress, String scAddress,


ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,

Department of Information Technology 20


Government College of Engineering, Karad AST Lab II

ArrayList<PendingIntent> deliveryIntents)
Send a multi-part text based SMS.

5 void sendTextMessage(String destinationAddress, String scAddress, String text,


PendingIntent sentIntent, PendingIntent deliveryIntent)
Send a text based SMS.

Example
Following example shows you in practical how to use SmsManager object to send an SMS
to the given mobile number.

To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.

Step Description

1 You will use Android Studio IDE to create an Android application and name it
as tutorialspoint under a package com.example.tutorialspoint.

2 Modify src/MainActivity.java file and add required code to take care of sending sms.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple GUI to take mobile number and SMS text to be sent and
a simple button to send SMS.

4 No need to define default string constants at res/values/strings.xml. Android studio


takes care of default constants.

5 Modify AndroidManifest.xml as shown below

6 Run the application to launch Android emulator and verify the result of the changes
done in the application.
Following is the content of the modified main activity
filesrc/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;

Department of Information Technology 21


Government College of Engineering, Karad AST Lab II

import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {

Department of Information Technology 22


Government College of Engineering, Karad AST Lab II

ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"

Department of Information Technology 23


Government College of Engineering, Karad AST Lab II

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending SMS Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Phone Number"
android:phoneNumber="true"
android:textColorHint="@color/abc_primary_text_material_dark"

Department of Information Technology 24


Government College of Engineering, Karad AST Lab II

android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"
android:hint="Enter SMS" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Sms"
android:id="@+id/btnSendSMS"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants –

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


<resources>
<string name="app_name">tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml –

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"

Department of Information Technology 25


Government College of Engineering, Karad AST Lab II

android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

I assume you have connected your actual Android Mobile device with your computer.
To run the app from Android studio, open one of your project's activity files and click
Run icon from the toolbar. Before starting your application, Android studio installer will
display following window to select an option where you want to run your Android
application

Fig 1: Sending SMS Example

Now you can enter a desired mobile number and a text message to be sent on that number.
Finally click on Send SMS button to send your SMS. Make sure your GSM/CDMA
connection is working fine to deliver your SMS to its recipient.

You can take a number of SMS separated by comma and then inside your program you will
have to parse them into an array string and finally you can use a loop to send message to all

Department of Information Technology 26


Government College of Engineering, Karad AST Lab II

the given numbers. That's how you can write your own SMS client. Next section will show
you how to use existing SMS client to send SMS.

 Using Built-in Intent to send SMS


You can use Android Intent to send SMS by calling built-in SMS functionality of the
Android. Following section explains different parts of our Intent object required to send an
SMS.

 Intent Object - Action to send SMS


You will use ACTION_VIEW action to launch an SMS client installed on your Android
device. Following is simple syntax to create an intent with ACTION_VIEW action.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object - Data/Type to send SMS


To send an SMS you need to specify smsto: as URI using setData() method and data type
will be to vnd.android-dir/mms-sms using setType() method as follows −

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

 Intent Object - Extra to send SMS


Android has built-in support to add phone number and text message to send an SMS as
follows −

smsIntent.putExtra("address" , new String("0123456789;3393993300"));


smsIntent.putExtra("sms_body" , "Test SMS to Angilla");
Here address and sms_body are case sensitive and should be specified in small characters
only. You can specify more than one number in single string but separated by semi-colon (;).
 Example
Following example shows you in practical how to use Intent object to launch SMS client to
send an SMS to the given recipients.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.
Step Description

1 You will use Android studio IDE to create an Android application and name it
as tutorialspoint under a package com.example.tutorialspoint.

2 Modify src/MainActivity.java file and add required code to take care of sending
SMS.

Department of Information Technology 27


Government College of Engineering, Karad AST Lab II

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple button to launch SMS Client.

4 No need to define default constants.Android studio takes care of default constants.

5 Modify AndroidManifest.xml as shown below

6 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity


filesrc/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startBtn = (Button) findViewById(R.id.button);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMS();
}
});
}
protected void sendSMS() {
Log.i("Send SMS", "");
Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Department of Information Technology 28


Government College of Engineering, Karad AST Lab II

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" , new String ("01234"));
smsIntent.putExtra("sms_body" , "Test ");
try {
startActivity(smsIntent);
finish();
Log.i("Finished sending SMS...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"

Department of Information Technology 29


Government College of Engineering, Karad AST Lab II

android:layout_height="wrap_content"
android:text="Drag and Drop Example"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point "
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Compose SMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>

Department of Information Technology 30


Government College of Engineering, Karad AST Lab II

Following will be the content of res/values/strings.xml to define two new constants −

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


<resources>
<string name="app_name">tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

 To run your this application. I assume you have connected your actual Android Mobile
device with your computer. To run the app from Android studio, open one of your
project's activity files and click Run icon from the toolbar. Before starting your
application, Android studio will display following window to select an option where you
want to run your Android application.

Department of Information Technology 31


Government College of Engineering, Karad AST Lab II

Fig 2: Select Mobile Device


Select your mobile device as an option and then check your mobile device which will
display following screen −

Fig 3: My Application
Now use Compose SMS button to launch Android built-in SMS clients which is shown
below −

Fig 4: Compose Screen

Department of Information Technology 32


Government College of Engineering, Karad AST Lab II

You can modify either of the given default fields and finally use send SMS button to send
your SMS to the mentioned recipient.
 Telephony- Phone calls
Android provides Built-in applications for phone calls, in some occasions we may need to make a
phone call through our application. This could easily be done by using implicit Intent with
appropriate actions. Also, we can use PhoneStateListener and TelephonyManager classes, in
order to monitor the changes in some telephony states on the device.
This chapter lists down all the simple steps to create an application which can be used to
make a Phone Call. You can use Android Intent to make phone call by calling built-in Phone
Call functionality of the Android. Following section explains different parts of our Intent
object required to make a call.
 Intent Object - Action to make Phone Call
You will use ACTION_CALL action to trigger built-in phone call functionality available in
Android device. Following is simple syntax to create an intent with ACTION_CALL action
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have
option to modify hardcoded phone number before making a call instead of making a direct
call.
 Intent Object - Data/Type to make Phone Call
To make a phone call at a given number 91-000-000-0000, you need to specify tel: as URI
using setData() method as follows −
phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
The interesting point is that, to make a phone call, you do not need to specify any extra data
or data type.
 Example
Following example shows you in practical how to use Android Intent to make phone call to
the given mobile number.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.

Step Description

1 You will use Android studio IDE to create an Android application and name it as My
Application under a packagecom.example.saira_000.myapplication.

2 Modify src/MainActivity.java file and add required code to take care of making a call.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple button to Call 91-000-000-0000 number

4 No need to define default string constants.Android studio takes care of default

Department of Information Technology 33


Government College of Engineering, Karad AST Lab II

constants.

5 Modify AndroidManifest.xml as shown below

6 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity filesrc/MainActivity.java.

package com.example.saira_000.myapplication;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonCall);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});
}

Department of Information Technology 34


Government College of Engineering, Karad AST Lab II

Following will be the content of res/layout/activity_main.xml file −

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 0377778888" />
</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants −

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


<resources>
<string name="app_name">My Application</string>
</resources>

Following is the default content of AndroidManifest.xml −

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.saira_000.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>

Department of Information Technology 35


Government College of Engineering, Karad AST Lab II

<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Let's try to run your My Application application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio, open one
of your project's activity files and click Run icon from the toolbar.Select your mobile device
as an option and then check your mobile device which will display following screen

Fig 5: My Application
Now use Call button to make phone call as shown below −

Fig 6: Dialling a number

Conclusion:- Thus, I have implemented Intents for SMS and Telephony.

Department of Information Technology 36


Government College of Engineering, Karad AST Lab II

Experiment No 4
Title: - Write a program to study and demonstrate Broadcast Receiver.

Outcome : - Students will be able to implement Broadcast Receiver in Android Applications.

Theory:-
 Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or
from the system itself. These messages are sometime called events or intents. For example,
applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver
who will intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
 Creating the Broadcast Receiver.
 Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then
you will have to create and broadcast those intents.
 Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
overriding the onReceive() method where each message is received as aIntent object
parameter.

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}

 Registering Broadcast Receiver


An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to registerMyReceiver for system
generated event ACTION_BOOT_COMPLETED which is fired by the system once the
Android system has completed the boot process.

Department of Information Technology 37


Government College of Engineering, Karad AST Lab II

FIG 1 : BROADCAST-RECEIVER

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>

Now whenever your Android device gets booted, it will be intercepted by


BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.

There are several system generated events defined as final static fields in theIntent class.
The following table lists a few important system events.

Sr.No Event Constant & Description

android.intent.action.BATTERY_CHANGED
1 Sticky broadcast containing the charging state, level, and other information about the
battery.

android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.

Department of Information Technology 38


Government College of Engineering, Karad AST Lab II

android.intent.action.BATTERY_OKAY
3
Indicates the battery is now okay after being low.

android.intent.action.BOOT_COMPLETED
4
This is broadcast once, after the system has finished booting.

android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.

android.intent.action.CALL
6
Perform a call to someone specified by the data.

android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for placing
a call.

android.intent.action.DATE_CHANGED
8
The date has changed.

android.intent.action.REBOOT
9
Have the device reboot.

 Broadcasting Custom Intents


If you want your application itself should generate and send custom intents then you will
have to create and send those intents by using the sendBroadcast()method inside your
activity class. If you use the sendStickyBroadcast(Intent)method, the Intent is sticky,
meaning the Intent you are sending stays around after the broadcast is complete.

public void broadcastIntent(View view) {


Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}

This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar way as


we have regsitered system generated intent.

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">

Department of Information Technology 39


Government College of Engineering, Karad AST Lab II

</action>
</intent-filter>
</receiver>
</application>

 Example
This example will explain you how to create BroadcastReceiver to intercept custom intent.
Once you are familiar with custom intent, then you can program your application to
intercept system generated intents. So let's follow the following steps to modify the Android
application we created in Hello World Example chapter −

Step Description

1 You will use Android studio to create an Android application and name it asMy
Application under a packagecom.example.tutorialspoint7.myapplication as explained
in the Hello World Example chapter.

2 Modify main activity file MainActivity.java to add broadcastIntent() method.

3 Create a new java file called MyReceiver.java under the


packagecom.example.tutorialspoint7.myapplication to define a BroadcastReceiver.

4 An application can handle one or more custom and system intents without any
restrictions. Every intent you want to intercept must be registered in
your AndroidManifest.xml file using <receiver.../> tag

5 Modify the default content of res/layout/activity_main.xml file to include a button to


broadcast intent.

6 No need to modify the string file, Android studio take care of string.xml file.

7 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity file MainActivity.java. This file can
include each of the fundamental life cycle methods. We have
addedbroadcastIntent() method to broadcast a custom intent.

package com.example.tutorialspoint7.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {

Department of Information Technology 40


Government College of Engineering, Karad AST Lab II

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// broadcast a custom intent.
public void broadcastIntent(View view){
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent);
}
}

Following is the content of MyReceiver.java:

package com.example.tutorialspoint7.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}

Following will the modified content of AndroidManifest.xml file. Here we have added
<receiver.../> tag to include our service:

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


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

Department of Information Technology 41


Government College of Engineering, Karad AST Lab II

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>

Following will be the content of res/layout/activity_main.xml file to include a button to


broadcast our custom intent −

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

Department of Information Technology 42


Government College of Engineering, Karad AST Lab II

android:layout_height="wrap_content"
android:text="Example of Broadcast"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Broadcast Intent"
android:onClick="broadcastIntent"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Let's try to run our modified Hello World! application we just modified. I assume you had
created your AVD while doing environment set-up. To run the app from Android studio,
open one of your project's activity files and click Run icon from the tool bar. Android

Department of Information Technology 43


Government College of Engineering, Karad AST Lab II

Studio installs the app on your AVD and starts it and if everything is fine with your set-up
and application, it will display following Emulator window −

FIG 2 : EXAMPLE OF BROADCAST


Now to broadcast our custom intent, let's click on Broadcast Intent button, this will
broadcast our custom intent "com.tutorialspoint.CUSTOM_INTENT"which will be
intercepted by our registered BroadcastReceiver i.e. MyReceiver and as per our
implemented logic a toast will appear on the bottom of the the simulator as follows −

FIG 3: Broadcast Intent


You can try implementing other BroadcastReceiver to intercept system generated intents
like system boot up, date changed, low battery etc.

Conclusion :- Thus, I have implemented Broadcast Receiver in Android Applications.

Department of Information Technology 44


Government College of Engineering, Karad AST Lab II

Experiment No 5
Title: - Write a program to demonstrate Spinners, Touch Mode, Alerts, Popups, and Toasts
with their events handler.

Outcome: - Students will be able to implement Spinners, Touch Mode, Alerts, Popups, and
Toasts with their events handler.

Theory:-

 Spinners
Spinners provide a quick way to select one value from a set. In the default state, a spinner
shows its currently selected value. Touching the spinner displays a dropdown menu with all
other available values, from which the user can select a new one.

Fig 1: Spinners
You can add a spinner to your layout with the Spinner object. You should usually do so in
your XML layout with a <Spinner> element. For example:

<Spinner
android:id="@+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

To populate the spinner with a list of choices, you then need to specify a SpinnerAdapter in
your Activity or Fragment source code.

 Populate the Spinner with User Choices

The choices you provide for the spinner can come from any source, but must be provided
through an SpinnerAdapter, such as an ArrayAdapter if the choices are available in an array
or a CursorAdapter if the choices are available from a database query.

For instance, if the available choices for your spinner are pre-determined, you can provide
them with a string array defined in a string resource file:

Department of Information Technology 45


Government College of Engineering, Karad AST Lab II

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


<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>

With an array such as this one, you can use the following code in
your Activity or Fragment to supply the spinner with the array using an instance
ofArrayAdapter:

Spinner spinner = (Spinner) findViewById(R.id.spinner);


// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);

The createFromResource() method allows you to create an ArrayAdapter from the string
array. The third argument for this method is a layout resource that defines how the selected
choice appears in the spinner control. The simple_spinner_item layout is provided by the
platform and is the default layout you should use unless you'd like to define your own layout
for the spinner's appearance.

You should then call setDropDownViewResource(int) to specify the layout the adapter
should use to display the list of spinner choices (simple_spinner_dropdown_item is another
standard layout defined by the platform).

Call setAdapter() to apply the adapter to your Spinner.

 Responding to User Selections

When the user selects an item from the drop-down, the Spinner object receives an on-item-
selected event.

Department of Information Technology 46


Government College of Engineering, Karad AST Lab II

To define the selection event handler for a spinner, implement the


AdapterView.OnItemSelectedListener interface and the correspondingonItemSelected()
callback method. For example, here's an implementation of the interface in an Activity:

public class SpinnerActivity extends Activity implements OnItemSelectedListener {


...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}

public void onNothingSelected(AdapterView<?> parent) {


// Another interface callback
}
}

The AdapterView.OnItemSelectedListener requires the onItemSelected() and


onNothingSelected() callback methods.

Then you need to specify the interface implementation by calling


setOnItemSelectedListener():

Spinner spinner = (Spinner) findViewById(R.id.spinner);


spinner.setOnItemSelectedListener(this);

If you implement the AdapterView.OnItemSelectedListener interface with your Activity or


Fragment (such as in the example above), you can pass this as the interface instance.

 Pickers
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.

Fig 2: Pickers
We recommend that you use DialogFragment to host each time or date picker.
The DialogFragment manages the dialog lifecycle for you and allows you to display the

Department of Information Technology 47


Government College of Engineering, Karad AST Lab II

pickers in different layout configurations, such as in a basic dialog on handsets or as an


embedded part of the layout on large screens.

Although DialogFragment was first added to the platform in Android 3.0 (API level 11), if
your app supports versions of Android older than 3.0—even as low as Android 1.6—you can
use the DialogFragment class that's available in the support library for backward
compatibility.
 Creating a Time Picker

To display a TimePickerDialog using DialogFragment, you need to define a fragment class


that extends DialogFragment and return a TimePickerDialogfrom the
fragment's onCreateDialog() method..

 Extending DialogFragment for a time picker

To define a DialogFragment for a TimePickerDialog, you must:

 Define the onCreateDialog() method to return an instance of TimePickerDialog

 Implement the TimePickerDialog.OnTimeSetListener interface to receive a callback when


the user sets the time.

Example:

public static class TimePickerFragment extends DialogFragment


implements TimePickerDialog.OnTimeSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

// Create a new instance of TimePickerDialog and return it


return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {


// Do something with the time chosen by the user
}
}

See the TimePickerDialog class for information about the constructor arguments.

Department of Information Technology 48


Government College of Engineering, Karad AST Lab II

Now all you need is an event that adds an instance of this fragment to your activity.

 Showing the time picker

Once you've defined a DialogFragment like the one shown above, you can display the time
picker by creating an instance of the DialogFragment and calling show().

For example, here's a button that, when clicked, calls a method to show the dialog:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_time"
android:onClick="showTimePickerDialog" />

When the user clicks this button, the system calls the following method:

public void showTimePickerDialog(View v) {


DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}

This method calls show() on a new instance of the DialogFragment defined above.
The show() method requires an instance of FragmentManager and a unique tag name for the
fragment.

 Creating a Date Picker

Creating a DatePickerDialog is just like creating a TimePickerDialog. The only difference is


the dialog you create for the fragment.

To display a DatePickerDialog using DialogFragment, you need to define a fragment class


that extends DialogFragment and return a DatePickerDialogfrom the
fragment's onCreateDialog() method.

 Extending DialogFragment for a date picker

To define a DialogFragment for a DatePickerDialog, you must:

 Define the onCreateDialog() method to return an instance of DatePickerDialog

 Implement the DatePickerDialog.OnDateSetListener interface to receive a callback when


the user sets the date.

Here's an example:

Department of Information Technology 49


Government College of Engineering, Karad AST Lab II

public static class DatePickerFragment extends DialogFragment


implements DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it


return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}

See the DatePickerDialog class for information about the constructor arguments.

Now all you need is an event that adds an instance of this fragment to your activity.

 Showing the date picker

Once you've defined a DialogFragment like the one shown above, you can display the date
picker by creating an instance of the DialogFragment and calling show().

For example, here's a button that, when clicked, calls a method to show the dialog:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_date"
android:onClick="showDatePickerDialog" />

When the user clicks this button, the system calls the following method:

public void showDatePickerDialog(View v) {


DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}

Department of Information Technology 50


Government College of Engineering, Karad AST Lab II

This method calls show() on a new instance of the DialogFragment defined above.
The show() method requires an instance of FragmentManager and a unique tag name for the
fragment.

 Toasts
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 on an email triggers a "Sending message..." toast, as shown in the
following screen capture:

Fig 3: Toast
If user response to a status message is required, consider instead using a Notification.

 The Basics

First, instantiate a Toast object with one of the makeText() methods. This method takes three
parameters: the application Context, the text message, and the duration for the toast. It returns
a properly initialized Toast object. You can display the toast notification with show(), as
shown in the following example:

Context context = getApplicationContext();


CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);


toast.show();

This example demonstrates everything you need for most toast notifications. You should
rarely need anything else. You may, however, want to position the toast differently or even
use your own layout instead of a simple text message. The following sections describe how
you can do these things.

Department of Information Technology 51


Government College of Engineering, Karad AST Lab II

You can also chain your methods and avoid holding on to the Toast object, like this:

Toast.makeText(context, text, duration).show();

 Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally.
You can change this position with the setGravity(int, int, int) method. This accepts three
parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the
gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To
nudge it down, increase the value of the last parameter.

 Creating a Custom Toast View

If a simple text message isn't enough, you can create a customized layout for your toast
notification. To create a custom layout, define a View layout, in XML or in your application
code, and pass the root View object to the setView(View) method.

For example, you can create the layout for the toast visible in the screenshot to the right with
the following XML (saved as layout/custom_toast.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"

Department of Information Technology 52


Government College of Engineering, Karad AST Lab II

/>
</LinearLayout>

Notice that the ID of the LinearLayout element is "custom_toast_container". You must use
this ID and the ID of the XML layout file "custom_toast" to inflate the layout, as shown here:

LayoutInflater inflater = getLayoutInflater();


View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_container));

TextView text = (TextView) layout.findViewById(R.id.text);


text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());


toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then
inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout
resource ID and the second is the root View. You can use this inflated layout to find more
View objects in the layout, so now capture and define the content for the ImageView and
TextView elements. Finally, create a new Toast with Toast(Context) and set some properties
of the toast, such as the gravity and duration. Then call setView(View) and pass it the inflated
layout. You can now display the toast with your custom layout by calling show().

 Creating a Popup Menu

Fig 4: Popup Menu

Department of Information Technology 53


Government College of Engineering, Karad AST Lab II

A PopupMenu is a modal menu anchored to a View. It appears below the anchor view if there
is room, or above the view otherwise. It's useful for:

 Providing an overflow-style menu for actions that relate to specific content (such as
Gmail's email headers, shown in figure 4).

 Providing a second part of a command sentence (such as a button marked "Add" that
produces a popup menu with different "Add" options).

 Providing a drop-down similar to Spinner that does not retain a persistent selection.

If you define your menu in XML, here's how you can show the popup menu:

1. Instantiate a PopupMenu with its constructor, which takes the current


application Context and the View to which the menu should be anchored.

2. Use MenuInflater to inflate your menu resource into the Menu object returned
by PopupMenu.getMenu().

3. Call PopupMenu.show().

For example, here's a button with the android:onClick attribute that shows a popup menu:

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_overflow_holo_dark"
android:contentDescription="@string/descr_overflow_button"
android:onClick="showPopup" />

The activity can then show the popup menu like this:

public void showPopup(View v) {


PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.actions, popup.getMenu());
popup.show();
}

In API level 14 and higher, you can combine the two lines that inflate the menu
with PopupMenu.inflate().

The menu is dismissed when the user selects an item or touches outside the menu area. You
can listen for the dismiss event usingPopupMenu.OnDismissListener.

Department of Information Technology 54


Government College of Engineering, Karad AST Lab II

 Handling click events

To perform an action when the user selects a menu item, you must implement
the PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by
calling setOnMenuItemclickListener(). When the user selects an item, the system calls
the onMenuItemClick() callback in your interface.

For example:

public void showMenu(View v) {


PopupMenu popup = new PopupMenu(this, v);

// This activity implements OnMenuItemClickListener


popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.actions);
popup.show();
}

@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.archive:
archive(item);
return true;
case R.id.delete:
delete(item);
return true;
default:
return false;
}
}

Conclusion: - Thus, I have to implemented Spinners, Touch Mode, Alerts, Popups, and
Toasts with their events handler.

Department of Information Technology 55


Government College of Engineering, Karad AST Lab II

Experiment No 6
Title: - Write a program to demonstrate Touch Mode, Menus with their events handler.

Outcome: - Students will be able to implement Touch Mode, Menus with their events
handler.

Theory:-

 Touch Mode

When a user is navigating a user interface with directional keys or a trackball, it is necessary
to give focus to actionable items (like buttons) so the user can see what will accept input. If
the device has touch capabilities, however, and the user begins interacting with the interface
by touching it, then it is no longer necessary to highlight items, or give focus to a particular
View. Thus, there is a mode for interaction named "touch mode."

For a touch-capable device, once the user touches the screen, the device will enter touch
mode. From this point onward, only Views for which isFocusableInTouchMode() is true will
be focusable, such as text editing widgets. Other Views that are touchable, like buttons, will
not take focus when touched; they will simply fire their on-click listeners when pressed.

Any time a user hits a directional key or scrolls with a trackball, the device will exit touch
mode, and find a view to take focus. Now, the user may resume interacting with the user
interface without touching the screen.

The touch mode state is maintained throughout the entire system (all windows and activities).
To query the current state, you can call isInTouchMode()to see whether the device is
currently in touch mode.

 Handling Focus

The framework will handle routine focus movement in response to user input. This includes
changing the focus as Views are removed or hidden, or as new Views become available.
Views indicate their willingness to take focus through the isFocusable() method. To change
whether a View can take focus, call setFocusable(). When in touch mode, you may query
whether a View allows focus with isFocusableInTouchMode(). You can change this
withsetFocusableInTouchMode().

Focus movement is based on an algorithm which finds the nearest neighbor in a given
direction. In rare cases, the default algorithm may not match the intended behavior of the
developer. In these situations, you can provide explicit overrides with the following XML
attributes in the layout file:nextFocusDown, nextFocusLeft, nextFocusRight,
and nextFocusUp. Add one of these attributes to the View from which the focus is leaving.

Department of Information Technology 56


Government College of Engineering, Karad AST Lab II

Define the value of the attribute to be the id of the View to which focus should be given. For
example:

<LinearLayout
android:orientation="vertical"
... >
<Button android:id="@+id/top"
android:nextFocusUp="@+id/bottom"
... />
<Button android:id="@+id/bottom"
android:nextFocusDown="@+id/top"
... />
</LinearLayout>

Ordinarily, in this vertical layout, navigating up from the first Button would not go anywhere,
nor would navigating down from the second Button. Now that the top Button has defined the
bottom one as the nextFocusUp (and vice versa), the navigation focus will cycle from top-to-
bottom and bottom-to-top.

If you'd like to declare a View as focusable in your UI (when it is traditionally not), add
the android:focusable XML attribute to the View, in your layout declaration. Set the
value true. You can also declare a View as focusable while in Touch Mode
with android:focusableInTouchMode.

To request a particular View to take focus, call requestFocus().

 Menus

Menus are a common user interface component in many types of applications. To provide a
familiar and consistent user experience, you should use the Menu APIs to present user actions
and other options in your activities.

Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required
to provide a dedicated Menu button. With this change, Android apps should migrate away
from a dependence on the traditional 6-item menu panel and instead provide an app bar to
present common user actions.

Although the design and user experience for some menu items have changed, the semantics
to define a set of actions and options is still based on the Menu APIs. This guide shows how
to create the three fundamental types of menus or action presentations on all versions of
Android:

Department of Information Technology 57


Government College of Engineering, Karad AST Lab II

 Options menu and app bar

The options menu is the primary collection of menu items for an activity. It's where you
should place actions that have a global impact on the app, such as "Search," "Compose
email," and "Settings."
 Context menu and contextual action mode
A context menu is a floating menu that appears when the user performs a long-click on an
element. It provides actions that affect the selected content or context frame.

The contextual action mode displays action items that affect the selected content in a bar at
the top of the screen and allows the user to select multiple items.

 Popup menu
A popup menu displays a list of items in a vertical list that's anchored to the view that
invoked the menu. It's good for providing an overflow of actions that relate to specific
content or to provide options for a second part of a command. Actions in a popup menu
should not directly affect the corresponding content—that's what contextual actions are for.
Rather, the popup menu is for extended actions that relate to regions of content in your
activity.
 Defining a Menu in XML
For all menu types, Android provides a standard XML format to define menu items. Instead
of building a menu in your activity's code, you should define a menu and all its items in an
XML menu resource. You can then inflate the menu resource (load it as a Menu object) in
your activity or fragment.

Using a menu resource is a good practice for a few reasons:

 It's easier to visualize the menu structure in XML.

 It separates the content for the menu from your application's behavioral code.

 It allows you to create alternative menu configurations for different platform versions, screen
sizes, and other configurations by leveraging the app resources framework.

To define the menu, create an XML file inside your project's res/menu/ directory and build
the menu with the following elements:

<menu>

Defines a Menu, which is a container for menu items. A <menu> element must be the root
node for the file and can hold one or more <item> and<group> elements.

<item>

Department of Information Technology 58


Government College of Engineering, Karad AST Lab II

Creates a MenuItem, which represents a single item in a menu. This element may contain a
nested <menu> element in order to create a submenu.

<group>

An optional, invisible container for <item> elements. It allows you to categorize menu items
so they share properties such as active state and visibility.

Here's an example menu named game_menu.xml:

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help" />
</menu>

The <item> element supports several attributes you can use to define an item's appearance
and behavior. The items in the above menu include the following attributes:

android:id

A resource ID that's unique to the item, which allows the application to recognize the item
when the user selects it.

android:icon

A reference to a drawable to use as the item's icon.

android:title

A reference to a string to use as the item's title.

android:showAsAction

Specifies when and how this item should appear as an action item in the app bar.

These are the most important attributes you should use, but there are many more available.

Department of Information Technology 59


Government College of Engineering, Karad AST Lab II

You can add a submenu to an item in any menu (except a submenu) by adding
a <menu> element as the child of an <item>. Submenus are useful when your application has
a lot of functions that can be organized into topics, like items in a PC application's menu bar
(File, Edit, View, etc.). For example:

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/file"
android:title="@string/file" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/create_new"
android:title="@string/create_new" />
<item android:id="@+id/open"
android:title="@string/open" />
</menu>
</item>
</menu>

To use the menu in your activity, you need to inflate the menu resource (convert the XML
resource into a programmable object) usingMenuInflater.inflate(). In the following sections,
you'll see how to inflate a menu for each menu type

 Creating an Options Menu

Fig 1: Creating an Options Menu

he options menu is where you should include actions and other options that are relevant to the
current activity context, such as "Search," "Compose email," and "Settings."

Department of Information Technology 60


Government College of Engineering, Karad AST Lab II

Where the items in your options menu appear on the screen depends on the version for which
you've developed your application:

 If you've developed your application for Android 2.3.x (API level 10) or lower, the
contents of your options menu appear at the bottom of the screen when the user presses
the Menu button, as shown in figure 1. When opened, the first visible portion is the icon
menu, which holds up to six menu items. If your menu includes more than six items,
Android places the sixth item and the rest into the overflow menu, which the user can
open by selectingMore.

 If you've developed your application for Android 3.0 (API level 11) and higher, items
from the options menu are available in the app bar. By default, the system places all items
in the action overflow, which the user can reveal with the action overflow icon on the right
side of the app bar (or by pressing the device Menu button, if available). To enable quick
access to important actions, you can promote a few items to appear in the app bar by
addingandroid:showAsAction="ifRoom" to the corresponding <item> elements (see
figure 2).

Figure 2: The Google Play Movies app, showing a search button and the action overflow
button.

You can declare items for the options menu from either your Activity subclass or
a Fragment subclass. If both your activity and fragment(s) declare items for the options menu,
they are combined in the UI. The activity's items appear first, followed by those of each
fragment in the order in which each fragment is added to the activity. If necessary, you can
re-order the menu items with the android:orderInCategory attribute in each <item> you
need to move.

To specify the options menu for an activity, override onCreateOptionsMenu() (fragments


provide their own onCreateOptionsMenu() callback). In this method, you can inflate your
menu resource (defined in XML) into the Menu provided in the callback. For example:

Department of Information Technology 61


Government College of Engineering, Karad AST Lab II

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}

You can also add menu items using add() and retrieve items with findItem() to revise their
properties with MenuItem APIs.

If you've developed your application for Android 2.3.x and lower, the system
calls onCreateOptionsMenu() to create the options menu when the user opens the menu for
the first time. If you've developed for Android 3.0 and higher, the system
calls onCreateOptionsMenu() when starting the activity, in order to show items to the app
bar.

 Handling click events

When the user selects an item from the options menu (including action items in the app bar),
the system calls your activity's onOptionsItemSelected()method. This method passes
the MenuItem selected. You can identify the item by calling getItemId(), which returns the
unique ID for the menu item (defined by the android:id attribute in the menu resource or
with an integer given to the add() method). You can match this ID against known menu items
to perform the appropriate action. For example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

When you successfully handle a menu item, return true. If you don't handle the menu item,
you should call the superclass implementation ofonOptionsItemSelected() (the default
implementation returns false).

Department of Information Technology 62


Government College of Engineering, Karad AST Lab II

If your activity includes fragments, the system first calls onOptionsItemSelected() for the
activity then for each fragment (in the order each fragment was added) until one
returns true or all fragments have been called.

 Changing menu items at runtime

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you
populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for
some reason. However, you should use onCreateOptionsMenu() only to create the initial
menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity
lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you
the Menu object as it currently exists so you can modify it, such as add, remove, or disable
items. (Fragments also provide anonPrepareOptionsMenu() callback.)

On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user
opens the options menu (presses the Menu button).

On Android 3.0 and higher, the options menu is considered to always be open when menu
items are presented in the app bar. When an event occurs and you want to perform a menu
update, you must call invalidateOptionsMenu() to request that the system
call onPrepareOptionsMenu().

 Creating Contextual Menus

Fig 3: Creating Contextual Menus

Department of Information Technology 63


Government College of Engineering, Karad AST Lab II

A contextual menu offers actions that affect a specific item or context frame in the UI. You
can provide a context menu for any view, but they are most often used for items in
a ListView, GridView, or other view collections in which the user can perform direct actions
on each item.

There are two ways to provide contextual actions:

 In a floating context menu. A menu appears as a floating list of menu items (similar to a
dialog) when the user performs a long-click (press and hold) on a view that declares
support for a context menu. Users can perform a contextual action on one item at a time.

 In the contextual action mode. This mode is a system implementation ofActionMode that
displays a contextual action bar at the top of the screen with action items that affect the
selected item(s). When this mode is active, users can perform an action on multiple items
at once (if your app allows it).

 Creating a floating context menu

To provide a floating context menu:

1. Register the View to which the context menu should be associated by


calling registerForContextMenu() and pass it the View.

If your activity uses a ListView or GridView and you want each item to provide the same
context menu, register all items for a context menu by passing
the ListView or GridView to registerForContextMenu().
2. Implement the onCreateContextMenu() method in your Activity or Fragment.

When the registered view receives a long-click event, the system calls
your onCreateContextMenu() method. This is where you define the menu items, usually
by inflating a menu resource. For example:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}

MenuInflater allows you to inflate the context menu from a menu resource. The callback
method parameters include the View that the user selected and
a ContextMenu.ContextMenuInfo object that provides additional information about the item

Department of Information Technology 64


Government College of Engineering, Karad AST Lab II

selected. If your activity has several views that each provide a different context menu, you
might use these parameters to determine which context menu to inflate.
3. Implement onContextItemSelected().

When the user selects a menu item, the system calls this method so you can perform the
appropriate action. For example:

@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
editNote(info.id);
return true;
case R.id.delete:
deleteNote(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}

The getItemId() method queries the ID for the selected menu item, which you should assign
to each menu item in XML using the android:idattribute, as shown in the section
about Defining a Menu in XML.
When you successfully handle a menu item, return true. If you don't handle the menu item,
you should pass the menu item to the superclass implementation. If your activity includes
fragments, the activity receives this callback first. By calling the superclass when unhandled,
the system passes the event to the respective callback method in each fragment, one at a time
(in the order each fragment was added) until true or false is returned. (The default
implementation for Activity and android.app.Fragment return false, so you should
always call the superclass when unhandled.)
 Using the contextual action mode
The contextual action mode is a system implementation of ActionMode that focuses user
interaction toward performing contextual actions. When a user enables this mode by selecting
an item, a contextual action bar appears at the top of the screen to present actions the user
can perform on the currently selected item(s). While this mode is enabled, the user can select
multiple items (if you allow it), deselect items, and continue to navigate within the activity
(as much as you're willing to allow). The action mode is disabled and the contextual action
bar disappears when the user deselects all items, presses the BACK button, or selects
the Done action on the left side of the bar.

Department of Information Technology 65


Government College of Engineering, Karad AST Lab II

For views that provide contextual actions, you should usually invoke the contextual action
mode upon one of two events (or both):

 The user performs a long-click on the view.

 The user selects a checkbox or similar UI component within the view.

How your application invokes the contextual action mode and defines the behavior for each
action depends on your design. There are basically two designs:

 For contextual actions on individual, arbitrary views.

 For batch contextual actions on groups of items in a ListView or GridView (allowing the
user to select multiple items and perform an action on them all).

The following sections describe the setup required for each scenario.

 Enabling the contextual action mode for individual views

If you want to invoke the contextual action mode only when the user selects specific views,
you should:

1. Implement the ActionMode.Callback interface. In its callback methods, you can specify
the actions for the contextual action bar, respond to click events on action items, and
handle other lifecycle events for the action mode.

2. Call startActionMode() when you want to show the bar (such as when the user long-clicks
the view).

For example:

1. Implement the ActionMode.Callback interface:

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

// Called when the action mode is created; startActionMode() was called


@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}

// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
@Override

Department of Information Technology 66


Government College of Engineering, Karad AST Lab II

public boolean onPrepareActionMode(ActionMode mode, Menu menu) {


return false; // Return false if nothing is done
}

// Called when the user selects a contextual menu item


@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
shareCurrentItem();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}

// Called when the user exits the action mode


@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};

Notice that these event callbacks are almost exactly the same as the callbacks for the options
menu, except each of these also pass the ActionModeobject associated with the event. You
can use ActionMode APIs to make various changes to the CAB, such as revise the title and
subtitle withsetTitle() and setSubtitle() (useful to indicate how many items are selected).
Also notice that the above sample sets the mActionMode variable null when the action mode
is destroyed. In the next step, you'll see how it's initialized and how saving the member
variable in your activity or fragment can be useful.
2. Call startActionMode() to enable the contextual action mode when appropriate, such as in
response to a long-click on a View:

someView.setOnLongClickListener(new View.OnLongClickListener() {
// Called when the user long-clicks on someView
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}

// Start the CAB using the ActionMode.Callback defined above


mActionMode = getActivity().startActionMode(mActionModeCallback);
view.setSelected(true);
return true;

Department of Information Technology 67


Government College of Engineering, Karad AST Lab II

}
});

When you call startActionMode(), the system returns the ActionMode created. By saving
this in a member variable, you can make changes to the contextual action bar in response
to other events. In the above sample, the ActionMode is used to ensure that
the ActionMode instance is not recreated if it's already active, by checking whether the
member is null before starting the action mode.
 Enabling batch contextual actions in a ListView or GridView
If you have a collection of items in a ListView or GridView (or another extension
of AbsListView) and want to allow users to perform batch actions, you should:

 Implement the AbsListView.MultiChoiceModeListener interface and set it for the view


group with setMultiChoiceModeListener(). In the listener's callback methods, you can
specify the actions for the contextual action bar, respond to click events on action items,
and handle other callbacks inherited from the ActionMode.Callback interface.

 Call setChoiceMode() with the CHOICE_MODE_MULTIPLE_MODAL argument.

For example:

ListView listView = getListView();


listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
}

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_delete:
deleteSelectedItems();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}

Department of Information Technology 68


Government College of Engineering, Karad AST Lab II

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context, menu);
return true;
}

@Override
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
}

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here you can perform updates to the CAB due to
// an invalidate() request
return false;
}
});

That's it. Now when the user selects an item with a long-click, the system calls
the onCreateActionMode() method and displays the contextual action bar with the specified
actions. While the contextual action bar is visible, users can select additional items.

In some cases in which the contextual actions provide common action items, you might want
to add a checkbox or a similar UI element that allows users to select items, because they
might not discover the long-click behavior. When a user selects the checkbox, you can invoke
the contextual action mode by setting the respective list item to the checked state
with setItemChecked()

Conclusion: - Thus, I have implemented Touch Mode, Menus with their events handler.

Department of Information Technology 69


Government College of Engineering, Karad AST Lab II

Experiment No 7
Title: - Write a program to demonstrate notification with their action.

Outcome: - Students will be able to demonstrate notification with their action.

Theory:-

 Notifications
A notification is a message you display to the user outside of your app's normal UI. When
you tell the system to issue a notification, it first appears as an icon in the notification area.
To see the details of the notification, the user opens the notification drawer. Both the
notification area and the notification drawer are system-controlled areas that the user can
view at any time.

Figure 1: Notifications in the notification area.

Figure 2: Notifications in the notification drawer.

In supported launchers and on devices running Android 8.0 (API level 26) and higher:

 Apps can also display notification badges on app icons.

 Users can also long-press on an app icon to glance at the notifications associated with a
notification badge.

Department of Information Technology 70


Government College of Engineering, Karad AST Lab II

Figure 3: Notification badges display on icons and folders.

Figure 4: Users can long-press on an app icon to glance at notifications.

 Design considerations
Notifications, as an important part of the Android user interface, have their own design
guidelines. The material design changes introduced in Android 5.0 (API level 21) are of
particular importance, and you should review the Material Design training for more
information.
 Managing notification channels
Starting in Android 8.0 (API level 26), notification channels allow you to create a user-
customizable channel for each type of notification you want to display. Notification channels
provide a unified system to help users manage notifications. When you target Android 8.0
(API level 26), you must implement one or more notification channels to display notifications
to your users. If you don't target Android 8.0 (API level 26) but your app is used on devices
running Android 8.0 (API level 26), your app behaves the same as it would on devices
running Android 7.1 (API level 25) or lower.
Users can manage most of the settings associated with notifications using a consistent system
UI. All notifications posted to the same notification channel have the same behavior. When a
user modifies the behavior for any of the following characteristics, it applies to the
notification channel:

 Importance

 Sound

Department of Information Technology 71


Government College of Engineering, Karad AST Lab II

 Lights

 Vibration

 Show on lockscreen

 Override do not disturb

Users can visit Settings, or long-press a notification to change these behaviors, or even block
a notification channel at any time. You can't programmatically modify the behavior of a
notification channel after it's created and submitted to the notification manager; the user is in
charge of those settings after creation. You can however rename a notification channel or
update its description after creation.

 Creating a notification channel

To create a notification channel:

1. Construct a notification channel object with an ID that's unique within your package.

2. Configure the notification channel object with any desired initial settings, such as an alert
sound, as well as an optional description visible to the user.

3. Submit the notification channel object to the notification manager.

Attempting to create an existing notification channel with its original values performs no
operation, so it's safe to perform the preceding sequence of steps when starting an app. The
following code sample demonstrates creating a notification channel with a high importance
level and a custom vibration pattern:

NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
// The user-visible name of the channel.
CharSequence name = getString(R.string.channel_name);
// The user-visible description of the channel.
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);

Department of Information Technology 72


Government College of Engineering, Karad AST Lab II

mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);

 Creating a notification channel group


If your app supports multiple user accounts, you can create a notification channel group for
each account. Notification channel groups allow you to manage multiple notification
channels with identical names within a single app. For example, a social networking app
might include support for personal and business user accounts. In this scenario, each user
account might require multiple notification channels with identical functions and names.
 A personal user account including 2 notification channels:

o Notifications of new comments on your posts.

o Notifications recommending posts by your contacts.

 A business user account including 2 notification channels:

o Notifications of new comments on your posts.

o Notifications recommending posts by your contacts.

Organizing the notification channels associated with each user account in this example into
dedicated groups ensures that users can easily distinguish between them in Settings. Each
notification channel group requires an ID that must be unique within your package, as well as
a user-visible name. The following snippet demonstrates how to create a notification channel
group.

// The id of the group.


String group = "my_group_01";
// The user-visible name of the group.
CharSequence name = getString(R.string.group_name);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(group, name));

After you've created a new group, you can call setGroup() to associate a new channel with the
group. You can only modify the association between notification channels and groups before
you submit the channel to the notification manager.
 Reading notification channel settings

Users can modify the settings for notification channels, including behaviors such as vibration
and alert sound. You can call the following two methods to discover the settings a user has
applied to a notification channel:

 To retrieve a single notification channel, you can call getNotificationChannel().

Department of Information Technology 73


Government College of Engineering, Karad AST Lab II

 To retrieve all notification channels belonging to your app, you can


call getNotificationChannels().

After you have the NotificationChannel, you can use methods such
as getVibrationPattern() and getSound() to find out what settings the user currently has. To
find out if a user blocked a notification channel, you can call getImportance(). If the
notification channel is blocked, getImportance()returns IMPORTANCE_NONE.

 Updating notification channel settings

After you create a notification channel, the user is in charge of its settings and behavior. You
can call createNotificationChannel() and then submit the notification channel again to the
notification manager to rename an existing notification channel, or update its description.

The following sample code describes how you can redirect a user to the settings for a
notification channel by creating an intent to start an activity. In this case, the intent requires
extended data, including the ID of the notification channel and the package name of your app.

Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);


intent.putExtra(Settings.EXTRA_CHANNEL_ID, mChannel.getId());
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(intent);

 Deleting a notification channel


You can delete notification channels by calling deleteNotificationChannel(). The following
sample code demonstrates how to complete this process:

NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
mNotificationManager.deleteNotificationChannel(id);

 Creating a notification
You specify the UI information and actions for a notification in
a NotificationCompat.Builder object. To create the notification itself, you
callNotificationCompat.Builder.build(), which returns a Notification object containing your
specifications. To issue the notification, you pass theNotification object to the system by
calling NotificationManager.notify().
 Required notification contents
A Notification object must contain the following:
 A small icon, set by setSmallIcon().
 A title, set by setContentTitle().

Department of Information Technology 74


Government College of Engineering, Karad AST Lab II

 Detail text, set by setContentText().


 On Android 8.0 (API level 26) and higher, a valid notification channel ID, set
by setChannelId() or provided in the NotificationCompat.Builderconstructor when
creating a channel.

 Optional notification contents and settings


All other notification settings and contents are optional.

 Notification actions

An action allows users to go directly from the notification to an Activity in your app, where
they can look at one or more events or do further work.

A notification can provide multiple actions. Make sure you always define the action that's
triggered when the user clicks the notification; usually this action opens an Activity in your
app. You can also add buttons to the notification that perform additional actions such as
snoozing an alarm or responding immediately to a text message; this feature is available as of
Android 4.1. If you use additional action buttons, you must also make their functionality
available in an Activity in your app; see the section Handling compatibility for more details.

Inside a Notification, the action itself is defined by a PendingIntent containing an Intent that
starts an Activity in your app. To associate thePendingIntent with a gesture, call the
appropriate method of NotificationCompat.Builder. For example, if you want to
start Activity when the user clicks the notification text in the notification drawer, you add
the PendingIntent by calling setContentIntent().

Starting an Activity when the user clicks the notification is the most common action scenario.
You can also start an Activity when the user dismisses a notification. In Android 4.1 and
later, you can start an Activity from an action button. To learn more, read the reference guide
forNotificationCompat.Builder.
 Notification priority and importance
If you wish, you can set the priority of a notification on Android 7.1 (API level 25) and
lower. The priority acts as a hint to the device UI about how the notification should be
displayed. To set a notification's priority, call NotificationCompat.Builder.setPriority() and
pass in one of theNotificationCompat priority constants. There are five priority levels,
ranging from PRIORITY_MIN (-2) to PRIORITY_MAX (2); if not set, the priority defaults
toPRIORITY_DEFAULT (0).
 Creating a simple notification

Remember that Android 8.0 (API level 26) and higher requires that you post notifications to a
notification channel. To learn how to create a notification channel, see Creating a notification
channel. The following snippet illustrates a simple notification that specifies an activity to

Department of Information Technology 75


Government College of Engineering, Karad AST Lab II

open when the user clicks the notification. Notice that the code creates
a TaskStackBuilder object and uses it to create the PendingIntent for the action. This pattern
is explained in more detail in the section Preserving Navigation when Starting an Activity:

// The id of the channel.


String CHANNEL_ID = "my_channel_01";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setChannelId(CHANNEL_ID);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// mNotificationId is a unique integer your app uses to identify the


// notification. For example, to cancel the notification, you can pass its ID
// number to NotificationManager.cancel().
mNotificationManager.notify(mNotificationId, mBuilder.build());

 Applying an expanded layout to a notification

To have a notification appear in an expanded view, first create


a NotificationCompat.Builder object with the normal view options you want. Next,
callBuilder.setStyle() with an expanded layout object as its argument.

Remember that expanded notifications are not available on platforms prior to Android 4.1. To
learn how to handle notifications for Android 4.1 and for earlier platforms, read the
section Handling compatibility.

Department of Information Technology 76


Government College of Engineering, Karad AST Lab II

For example, the following code snippet demonstrates how to alter the notification created in
the previous snippet to use the expanded layout:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)


.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Event tracker")
.setContentText("Events received")
.setChannelId(CHANNEL_ID);
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
...
// Moves events into the expanded layout
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inboxStyle);
...
// Issue the notification here.

 Handling compatibility
Not all notification features are available for a particular version, even though the methods to
set them are in the support library classNotificationCompat.Builder. For example, action
buttons, which depend on expanded notifications, only appear on Android 4.1 and higher,
because expanded notifications themselves are only available on Android 4.1 and higher.
To ensure the best compatibility, create notifications with NotificationCompat and its
subclasses, particularly NotificationCompat.Builder. In addition, follow this process when
you implement a notification:

1. Provide all of the notification's functionality to all users, regardless of the version they're
using. To do this, verify that all of the functionality is available from an Activity in your
app. You may want to add a new Activity to do this.

For example, if you want to use addAction() to provide a control that stops and starts
media playback, first implement this control in an Activity in your app.
2. Ensure that all users can get to the functionality in the Activity, by having it start when
users click the notification. To do this, create a PendingIntentfor the Activity.
Call setContentIntent() to add the PendingIntent to the notification.

Department of Information Technology 77


Government College of Engineering, Karad AST Lab II

3. Now add the expanded notification features you want to use to the notification. Remember
that any functionality you add also has to be available in the Activity that starts when
users click the notification.

 Managing notifications

When you need to issue a notification multiple times for the same type of event, you should
avoid making a completely new notification. Instead, you should consider updating a
previous notification, either by changing some of its values or by adding to it, or both.

For example, Gmail notifies the user that new emails have arrived by increasing its count of
unread messages and by adding a summary of each email to the notification. This is called
"stacking" the notification; it's described in more detail in the Notifications Design guide.

The following section describes how to update notifications and also how to remove them.

 Updating notifications

To set up a notification so it can be updated, issue it with a notification ID by


calling NotificationManager.notify(). To update this notification after you've issued it, update
or create a NotificationCompat.Builder object, build a Notification object from it, and issue
the Notification with the same ID you used previously. If the previous notification is still
visible, the system updates it from the contents of the Notification object. If the previous
notification has been dismissed, a new notification is created instead.

The following snippet demonstrates a notification that is updated to reflect the number of
events that have occurred. It stacks the notification, showing a summary:

mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID);
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(

Department of Information Technology 78


Government College of Engineering, Karad AST Lab II

notifyID,
mNotifyBuilder.build());
...

 Removing notifications
Notifications remain visible until one of the following happens:
 The user dismisses the notification either individually or by using "Clear All" (if the
notification can be cleared).
 The user clicks the notification, and you called setAutoCancel() when you created the
notification.
 You call cancel() for a specific notification ID. This method also deletes ongoing
notifications.
 You call cancelAll(), which removes all of the notifications you previously issued.
 If you set a timeout when creating a notification using setTimeoutAfter(), the system
cancels the notification after the specified duration elapses. If required, you can cancel a
notification before the specified timeout duration elapses.
 Removing notifications
Android 8.0 (API level 26) introduces functionality for displaying notification badges on app
icons in supported launchers. Notification badges show notifications associated with one or
more notification channels in an app, which the user has not yet dismissed or acted on. Users
can turn off badges for notification channels or apps from the Settings app. Notification
badges are also known as notification dots).

Users can also long-press on an app icon to glance at the notifications associated with a
notification badge in supported launchers. Users can then dismiss or act on notifications from
the long-press menu in a similar way to the notification drawer.

Figure 5: You can override the notification count displayed in the long-press menu.
A folder's notification badge indicates the presence of notification badges for one or more of
the apps inside the folder.

Department of Information Technology 79


Government College of Engineering, Karad AST Lab II

Consider the following examples when planning to create notifications in a notification


channel for your app:
 Ongoing notifications: Most ongoing notifications, such as image processing, media
playback controls, or current navigation instructions, don't make sense as a badge.
 Calendaring apps: Avoid badging events occurring at the current time.
 Clock or alarm apps: Avoid badging notifications related to current alarms.
 Adjusting notification badges
By default, each notification channel reflects its active notifications in your app's launcher
icon badge. You can use the setShowBadge() method to stop the presence of notifications
from a channel being reflected by a badge. You can't programmatically modify this setting
for a notification channel after it's created and submitted to the notification manager.
The following sample code illustrates how to hide badges in association with notifications
from a notification channel:

NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The ID of the channel.
String id = "my_channel_01";
// The user visible name of the channel.
CharSequence name = getString(R.string.channel_name);
// The user visible description of the channel.
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.setShowBadge(false);
mNotificationManager.createNotificationChannel(mChannel);

You can call setNumber() to set a custom number to display in the long-press menu of an app
in supported launchers, as illustrated by the following sample code for a messaging app:

mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


int notificationID = 1;
String CHANNEL_ID = "my_channel_01";
// Set a message count to associate with this notification in the long-press menu.
int messageCount = 3;
// Create a notification and set a number to associate with it.
NotificationCompat notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("New Messages")
.setContentText("You've received 3 new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.setNumber(messageCount)

Department of Information Technology 80


Government College of Engineering, Karad AST Lab II

.build();
// Issue the notification.
mNotificationManager.notify(notificationID, notification);

The long-press menu displays the large or small icon associated with a notification if
available. By default, the system displays the large icon, but you can
call NotificationCompat.Builder.setBadgeIconType() and pass in
the BADGE_ICON_SMALL constant to display the small icon.

If your app creates a notification that duplicates a shortcut, you can temporarily hide the
shortcut while the notification is active. To hide a shortcut while a notification is active,
call setShortcutId() and pass the ID of the shortcut.

 Replying to notifications

Starting in Android 7.0 (API level 24), users can respond directly to text messages or update
task lists from within the notification dialog. On a handheld, the inline reply action appears as
an additional button displayed in the notification. When a user replies via keyboard, the
system attaches the text response to the intent you had specified for the notification action
and sends the intent to your handheld app.

Figure 6: The Reply action button.

 Adding inline reply actions


To create a notification action that supports direct reply:
1. Create an instance of RemoteInput.Builder that you can add to your notification action.
This class's constructor accepts a string that the system uses as the key for the text input.
Later, your handheld app uses that key to retrieve the text of the input.

// Key for the string that's delivered in the action's intent.


private static final String KEY_TEXT_REPLY = "key_text_reply";
String replyLabel = getResources().getString(R.string.reply_label);
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)

Department of Information Technology 81


Government College of Engineering, Karad AST Lab II

.setLabel(replyLabel)
.build();

2. Attach the RemoteInput object to an action using addRemoteInput().

// Create the reply action and add the remote input.


Notification.Action action =
new Notification.Action.Builder(R.drawable.ic_reply_icon,
getString(R.string.label), replyPendingIntent)
.addRemoteInput(remoteInput)
.setChannelId(CHANNEL_ID)
.build();

3. Apply the action to a notification and issue the notification.

// Build the notification and add the action.


Notification newMessageNotification =
new Notification.Builder(mContext)
.setSmallIcon(R.drawable.ic_message)
.setContentTitle(getString(R.string.title))
.setContentText(getString(R.string.content))
.addAction(action))
.build();

// Issue the notification.


NotificationManager notificationManager =
NotificationManager.from(mContext);
notificationManager.notify(notificationId, newMessageNotification);

The system prompts the user to input a response when they trigger the notification action.

Figure 7: The user inputs text from the notification shade.

Department of Information Technology 82


Government College of Engineering, Karad AST Lab II

 Retrieving user input from the inline reply


To receive user input from the notification interface to the activity you declared in the reply
action's intent:
1. Call getResultsFromIntent() by passing the notification action's intent as the input
parameter. This method returns a Bundle that contains the text response.

Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);

2. Query the bundle using the result key (provided to the RemoteInput.Builder constructor).
You can complete this process and retrieve the input text by creating a method, as in the
following code snippet:

// Obtain the intent that started this activity by calling


// Activity.getIntent() and pass it into this method to
// get the associated string.

private CharSequence getMessageText(Intent intent) {


Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
return remoteInput.getCharSequence(KEY_TEXT_REPLY);
}
return null;
}

3. Build and issue another notification, using the same notification ID that you provided for
the previous notification. The progress indicator disappears from the notification interface
to inform users of a successful reply. When working with this new notification, use the
context that gets passed to the receiver's onReceive() method.

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
Notification repliedNotification =
new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_message)
.setContentText(getString(R.string.replied))
.setChannelId(CHANNEL_ID)
.build();

// Issue the new notification.


NotificationManager notificationManager =
NotificationManager.from(context);
notificationManager.notify(notificationId, repliedNotification);

For interactive apps, such as chats, you can include additional context when handling
retrieved text. For example, these apps could show multiple lines of chat history. When the

Department of Information Technology 83


Government College of Engineering, Karad AST Lab II

user responds via RemoteInput, you can update the reply history using
the setRemoteInputHistory() method.

The notification must be either updated or cancelled after the app has received remote input.
When the user replies to a remote update using Direct Reply, do not cancel the notification.
Instead, update the notification to display the user's reply. For notifications
using MessagingStyle, you should add the reply as the latest message. When using other
templates, you can append the user's reply to the remote-input history.

Conclusion: - Thus, I have demonstrated notification with their action.

Department of Information Technology 84


Government College of Engineering, Karad AST Lab II

Experiment No 8
Title: - Write a program to study and use of SQLite database.

Outcome: - Students will be able to implement SQLite database in Android Applications.

Theory:-

SQLite is a opensource SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you
don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

 Database - Package
The main package is android.database.sqlite that contains the classes to manage your own
databases

 Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with
your database name and mode as a parameter. It returns an instance of SQLite database
which you have to receive in your own object.Its syntax is given below

SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);

Apart from this , there are other functions available in the database package , that does this
job. They are listed below

Sr.No Method & Description

1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,


DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The
common flags mode could be OPEN_READWRITE OPEN_READONLY

2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)


It is similar to the above method as it also opens the existing database but it does not
define any handler to handle the errors of databases

3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)


It not only opens but create the database if it not exists. This method is equivalent to
openDatabase method.

4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)


This method is similar to above method but it takes the File object as a path rather then

Department of Information Technology 85


Government College of Engineering, Karad AST Lab II

a string. It is equivalent to file.getPath()

 Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password


VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

This will insert some values into our table in our database. Another method that also does
the same job but take some additional parameter is given below

Sr.No Method & Description

1 execSQL(String sql, Object[] bindArgs)


This method not only insert data , but also used to update or modify already
existing data in database using bind arguments

 Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to
the table. We can move the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);


resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve
the data. That includes

Sr.No Method & Description

1 getColumnCount()
This method return the total number of columns of the table.

2 getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column

3 getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column

4 getColumnNames()
This method returns the array of all the column names of the table.

Department of Information Technology 86


Government College of Engineering, Karad AST Lab II

5 getCount()
This method returns the total number of rows in the cursor

6 getPosition()
This method returns the current position of the cursor in the table

7 isClosed()
This method returns true if the cursor is closed and return false otherwise

 Database - Helper class


For managing all the operations related to the database , an helper class has been given and
is called SQLiteOpenHelper. It automatically manages the creation and update of the
database. Its syntax is given below

public class DBHelper extends SQLiteOpenHelper {


public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

Example
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera
is supported.

Steps Description

1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to get references of all the XML components and populate the contacts
on listView.

3 Create new src/DBHelper.java that will manage the database work

4 Create a new Activity as DisplayContact.java that will display the contact on the screen

5 Modify the res/layout/activity_main to add respective XML components

6 Modify the res/layout/activity_display_contact.xml to add respective XML components

7 Modify the res/values/string.xml to add necessary string components

Department of Information Technology 87


Government College of Engineering, Karad AST Lab II

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

10 Run the application and choose a running android device and install the application on it and verify the
results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {


public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

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

Department of Information Technology 88


Government College of Engineering, Karad AST Lab II

mydb = new DBHelper(this);


ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;

Bundle dataBundle = new Bundle();


dataBundle.putInt("id", id_To_Search);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

intent.putExtras(dataBundle);
startActivity(intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);

Department of Information Technology 89


Government College of Engineering, Karad AST Lab II

switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);


intent.putExtras(dataBundle);

startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

public boolean onKeyDown(int keycode, KeyEvent event) {


if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}

Following is the modified content of display contact activityDisplayContact.java

package com.example.sairamkrishna.myapplication;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

import android.view.Menu;
import android.view.MenuItem;

Department of Information Technology 90


Government College of Engineering, Karad AST Lab II

import android.view.View;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayContact extends Activity {


int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;

TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);

mydb = new DBHelper(this);

Bundle extras = getIntent().getExtras();


if(extras !=null) {
int Value = extras.getInt("id");

if(Value>0){
//means this is the view part not the add contact part.

Department of Information Technology 91


Government College of Engineering, Karad AST Lab II

Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();

String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));


String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));

if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);

name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);

phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);

email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);

street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);

place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);

Department of Information Technology 92


Government College of Engineering, Karad AST Lab II

}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();

if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}

public boolean onOptionsItemSelected(MenuItem item) {


super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);

phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);

email.setEnabled(true);

Department of Information Technology 93


Government College of Engineering, Karad AST Lab II

email.setFocusableInTouchMode(true);
email.setClickable(true);

street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);

place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);

return true;
case R.id.Delete_Contact:

AlertDialog.Builder builder = new AlertDialog.Builder(this);


builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});

AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();

Department of Information Technology 94


Government College of Engineering, Karad AST Lab II

return true;
default:
return super.onOptionsItemSelected(item);

}
}

public void run(View view) {


Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(),
phone.getText().toString(), email.getText().toString(),
street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(),
email.getText().toString(), street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}

Department of Information Technology 95


Government College of Engineering, Karad AST Lab II

}
}

Following is the content of Database class DBHelper.java

package com.example.sairamkrishna.myapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";


public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;

public DBHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {

Department of Information Technology 96


Government College of Engineering, Karad AST Lab II

// TODO Auto-generated method stub


db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}

public boolean insertContact (String name, String phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}

public Cursor getData(int id) {


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}

public int numberOfRows(){


SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);

Department of Information Technology 97


Government College of Engineering, Karad AST Lab II

return numRows;
}

public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}

public Integer deleteContact (Integer id) {


SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}

public ArrayList<String> getAllCotacts() {


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

//hp = new HashMap();


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();

while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;

Department of Information Technology 98


Government College of Engineering, Karad AST Lab II

}
}

Following is the content of the res/layout/activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"

Department of Information Technology 99


Government College of Engineering, Karad AST Lab II

android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>

</ScrollView>

</RelativeLayout>

Following is the content of the res/layout/activity_display_contact.xml

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


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"

Department of Information Technology 100


Government College of Engineering, Karad AST Lab II

android:layout_height="wrap_content"
tools:context=".DisplayContact" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>

<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

Department of Information Technology 101


Government College of Engineering, Karad AST Lab II

android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView

Department of Information Technology 102


Government College of Engineering, Karad AST Lab II

android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"

Department of Information Technology 103


Government College of Engineering, Karad AST Lab II

android:ems="10"
android:inputType="text" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />

</RelativeLayout>
</ScrollView>

Following is the content of the res/value/string.xml

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


<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete it.</string>

Department of Information Technology 104


Government College of Engineering, Karad AST Lab II

<string name="yes">Yes</string>
<string name="no">No</string>
</resources>

Following is the content of the res/menu/main_menu.xml

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


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

<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>

</menu>

Following is the content of the res/menu/display_contact.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>

<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>

</menu>

This is the defualt AndroidManifest.xml of this project

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


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

Department of Information Technology 105


Government College of Engineering, Karad AST Lab II

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

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

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile
device with your computer. To run the app from Android studio , open one of your project's
activity files and click Run icon from the tool bar. Before starting your
application,Android studio will display following window to select an option where you
want to run your Android application.

Department of Information Technology 106


Government College of Engineering, Karad AST Lab II

Fig 1: Choose Device


Select your mobile device as an option and then check your mobile device which will
display following screen −

Fig 2: Run Application


Now open your optional menu, it will show as below image: Optional menu appears
different places on different versions

Fig 3: Add New Data

Department of Information Technology 107


Government College of Engineering, Karad AST Lab II

Click on the add button of the menu screen to add a new contact. It will display the
following screen −

Fig 4: Save Contact


It will display the following fields. Please enter the required information and click on save
contact. It will bring you back to main screen.

Fig 5: Main Screen


Now our contact sai has been added.In order to see that where is your database is created.
Open your android studio, connect your mobile. Gotools/android/android device monitor.
Now browse the file explorer tab. Now browse this
folder/data/data/<your.package.name>/databases<database-name>.

Conclusion: - Thus. I have implemented SQLite database in Android Applications.

Department of Information Technology 108


Government College of Engineering, Karad AST Lab II

EXPERIMENT NO 9

Title: Implement web application using ASP.NET with web control and provide input
validations using input valuators.

Outcome: Students will be able to understand different validators in asp.net.

Theory:

ASP.Net validation controls validate the user input data to ensure that useless,
unauthenticated or contradictory data don.t get stored.
ASP.Net provides the following validation controls:
 RequiredFieldValidator
 RangeValidator
 CompareValidator
 RegularExpressionValidator
 CustomValidator
 ValidationSummary

 The BaseValidator Class:

The validation control classes inherit from the BaseValidator class and inherit its
properties and methods. Therefore, it would help to take a look at the properties and
the methods of this base class, which are common for all the validation controls:

Members Description
ControlToValidate Indicates the input control to validate.
Display Indicates how the error message is shown.
EnableClientScript Indicates whether client side validation will take.
Enabled Enables or disables the validator.
ErrorMessage Error string.
Text Error text to be shown if validation fails.
IsValid Indicates whether the value of the control is valid.
SetFocusOnError It indicates whether in case of an invalid control, the focus should
switch to the related input control.
ValidationGroup The logical group of multiple validators, where this control belongs.
Validate() This method revalidates the control and updates the IsValid
property.

 The RequiredFieldValidator:

The RequiredFieldValidator control ensures that the required field is not empty. It is

Department of Information Technology 109


Government College of Engineering, Karad AST Lab II

generally tied to a text box to force input into the text box.
The syntax for the control:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a

candidate" InitialValue="Please choose a


candidate">

</asp:RequiredFieldValidator>

 The RangeValidator:

The RangeValidator control verifies that the input value falls within a predetermined
range.
It has three specific properties:

Properties Description
Type it defines the type of the data; the available values are: Currency,
Date, Double, Integer and String
MinimumValue it specifies the minimum value of the range
MaximumValue it specifies the maximum value of the range

The syntax for the control:


<asp:RangeValidator ID="rvclass"
runat="server"
ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)"
MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>

 The CompareValidator:

The CompareValidator control compares a value in one control with a fixed value, or, a
value in another control.
It has the following specific properties:

Properties Description
Type it specifies the data type
ControlToCompare it specifies the value of the input control to compare with
ValueToCompare it specifies the constant value to compare with

Department of Information Technology 110


Government College of Engineering, Karad AST Lab II

Operator it specifies the comparison operator, the available values are: Equal,
NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual
and DataTypeCheck

The basic syntax for the control:


<asp:CompareValidator ID="CompareValidator1"
runat="server"
ErrorMessage="CompareValidator">
</asp:CompareValidator>

 The RegularExpressionValidator

The RegularExpressionValidator allows validating the input text by matching against a


pattern against a regular expression. The regular expression is set in the
ValidationExpression property.

The following table summarizes the commonly used syntax constructs for regular
expressions:
Character Escapes Description
\b Matches a backspace
\t Matches a tab
\r Matches a carriage return
\v Matches a vertical tab
\f Matches a form feed
\ Escape character

Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.

Metacharacters Description
. Matches any character except \n
[abcd] Matches any character in the set
[^abcd] Excludes any character in the set
[2-7a-mA-M] Matches any character specified in the range
\w Matches any alphanumeric character and underscore
\W Matches any non-word character
\s Matches whitespace characters like, space, tab, new line etc.
\S Matches any non-whitespace character
\d Matches any decimal character
\D Matches any non-decimal character

Department of Information Technology 111


Government College of Engineering, Karad AST Lab II

Quantifiers could be added to specify number of times a character could appear

Quantifier Description
* Zero or more matches
+ One or more matches
? Zero or one matches
{N} N matches
{N,} N or more matches
{N,M} Between N and M matches

The syntax for the control:


<asp:RegularExpressionValidator ID="string"
runat="server"
ErrorMessage="string"
ValidationExpression="string"
ValidationGroup="string">
</asp:RegularExpressionValidator>

 The CustomValidator:

The CustomValidator control allows writing application specific custom validation


routines for both the client side and the server side validation. The client side validation is
accomplished through the ClientValidationFunction property. The client side validation
routine should be written in a scripting language, like JavaScript or VBScript, which the
browser can understand. The server side validation routine must be called from the
control.s ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or VB.Net.
The basic syntax for the control
<asp:CustomValidator ID="CustomValidator1"
runat="server"
ClientValidationFunction=.cvf_func.
ErrorMessage="CustomValidator">
</asp:CustomValidator>

 The ValidationSummary Control

The ValidationSummary control does not perform any validation but shows a summary
of all errors in the page. The summary displays the values of the ErrorMessage property
of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
 ShowSummary: shows the error messages in specified format.
 ShowMessageBox: shows the error messages in a separate window.

Department of Information Technology 112


Government College of Engineering, Karad AST Lab II

The syntax for the control:


<asp:ValidationSummary ID="ValidationSummary1"
runat="server"
DisplayMode = "BulletList"
ShowSummary = "true"
HeaderText="Errors:" />

 Validation Groups:

Complex pages have different groups of information provided in different panels. In such
a situation a need for performing validation separately for separate group, might arise.
This kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation controls
into the same logical group by setting their ValidationGroup property.

Questions:

1. List different validators present in ASP.NET.


2. Where should we use the validators?
3. How to change the default validation message for validators?

Conclusion : Thus, I have studied different validators in ASP.Net.

Department of Information Technology 113


Government College of Engineering, Karad AST Lab II

EXPERIMENT NO 10

Title: Create a Web application that illustrates the use of themes and master pages with Site-
Map. And create a web page with CSS.

Outcome: Students will be able to understand use of themes and master pages with Site-Map
and will able to create a web page with CSS in asp.net.

Theory:

Themes
Themes are also a new feature of ASP.NET that helps maintain a consistent look and feel
across all or several pages of our web site. Themes are needed when we want to keep the
style and layout information files separate from other web site files. Themes are included
images and skin files; the skin files set the visual properties of ASP.NET controls. Themes
are of two types:

Let's create a theme application with the help of the following steps:
Step 1 : Open Microsoft Visual Studio 2010.
Step 2 : Select File->New->Web Site.
Step 3 : Select ASP.NET Web Site and then click Ok.
Step 4 : Now right-click in the application name in the Solution Explorer window and select
Add ->ASP.NET Folder->Theme from the context menu.

Figure. 1: Add theme in ASP.NET Folder

A sub folder named Theme1 is automatically created inside the APP_Themes folder in the
SolutionExplorer.

Department of Information Technology 114


Government College of Engineering, Karad AST Lab II

Figure. 2: APP_Themes folder

Step 5 : Right-click on the Theme1 folder and select the Add New Item option.
Step 6 : Select the Skin file and click the Add button.

Figure. 3: Skin File

Now write the following code in the skin file.

Department of Information Technology 115


Government College of Engineering, Karad AST Lab II

Step 7 : The design window will look like:

Figure. 4: Design window

Step 8 : Now Press F5 key to run the application.

Figure 5: Output of application

Master Page:
Master page provides the layout and functionality to the other pages. Creating a master page
in ASP.NET is very easy. Let's start creating master page step by step.
Step 1: Open new project in visual studio
New project->Installed->Web->ASP.NET Web Application
Step 2: Add new file in to our project.
Add the master page into our project.
Right click Project->Add->New item (shown in the picture),
After clicking on new item, Window will open, select Web Form->Web Forms Master Page
(shown in the picture),

Department of Information Technology 116


Government College of Engineering, Karad AST Lab II

Figure 6: Add Master Page


After clicking the add button, master page 'site1.master' adds to our project. Click on
site1.master into Solution Explorer.
Step 3: Design the master page, using HTML
HTML code of my master page is,

1. <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.c


s" Inherits="masterpage.Site1" %>
2.
3. <!DOCTYPE html>
4.
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title>c# corner</title>
8. <link href="css/my.css" rel="stylesheet" />
9. <asp:ContentPlaceHolder ID="head" runat="server">
10. </asp:ContentPlaceHolder>
11. </head>
12. <body>
13. <!DOCTYPE html>
14. <html>
15. <head>
16. <title>my layout</title>
17. <link rel="stylesheet" type="text/css" href="my.css">
18. </head>
19. <body>

Department of Information Technology 117


Government College of Engineering, Karad AST Lab II

20. <header id="header">


21. <h1>c# corner</h1>
22. </header>
23. <nav id="nav">
24. <ul>
25. <li><a href="home.aspx">Home</a></li>
26. <li><a href="#">About</a></li>
27. <li><a href="#">Article</a></li>
28. <li><a href="#">Contact</a></li>
29. </ul>
30. </nav>
31. <aside id="side">
32. <h1>news</h1>
33. <a href="#"><p>creating html website</p></a>
34. <a href="#"><p>learn css</p></a>
35. <a href="#">learn c#</a>
36. </aside>
37.
38.
39. <div id="con">
40. <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
41.
42. </asp:ContentPlaceHolder>
43. </div>
44.
45.
46. <footer id="footer">
47. copyright @c# corner
48. </footer>
49. </body>
50. </html>
51. <form id="form1" runat="server">
52.
53. </form>
54. </body>
55. </html>

CSS Code

1. #header{
2. color: #247BA0;
3. text-align: center;

Department of Information Technology 118


Government College of Engineering, Karad AST Lab II

4. font-size: 20px;
5. }
6. #nav{
7. background-color:#FF1654;
8. padding: 5px;
9. }
10. ul{
11.
12. list-style-type: none;
13. }
14. li a {
15. color: #F1FAEE;
16. font-size: 30px;
17. column-width: 5%;
18. }
19. li
20. {
21. display: inline;
22. padding-left: 2px;
23. column-width: 20px;
24. }
25. a{
26. text-decoration: none;
27. margin-left:20px
28. }
29. li a:hover{
30. background-color: #F3FFBD;
31. color: #FF1654;
32. padding:1%;
33. }
34. #side{
35. text-align: center;
36. float: right;
37. width: 15%;
38. padding-bottom: 79%;
39. background-color: #F1FAEE;
40. }
41. #article{
42. background-color: #EEF5DB;
43. padding: 10px;
44. padding-bottom: 75%;
45. }
46. #footer{
47. background-color: #C7EFCF;

Department of Information Technology 119


Government College of Engineering, Karad AST Lab II

48. text-align:center;
49. padding-bottom: 5%;
50. font-size: 20px;
51. }
52. #con{
53. border:double;
54. }
55.

Step 4: Add web form in to our project.


Right click on the project->Add->New item (shown in the picture),
Select Web form with the master page.

Figure 7: Add Web form


After clicking on that, add the button Window, open the selected masterpage->site1.master
and click OK.

Department of Information Technology 120


Government College of Engineering, Karad AST Lab II

Fiure 8: selected masterpage->site1.master


Now, design our homepage.
Here, we write home page only,
Home.aspx
1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWi
reup="true" CodeBehind="home.aspx.cs" Inherits="masterpage.home" %>
2. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
3. </asp:Content>
4. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="
server">
5. <h1>Home page</h1>
6. </asp:Content>
Finally, our Master page is created; build and run the project.

Figure 9: Ouput of project

Department of Information Technology 121


Government College of Engineering, Karad AST Lab II

SiteMap:
The SiteMapPath control basically is used to access web pages of the website from one
webpage to another. The SiteMapPath control basically is used to access web pages of the
website from one webpage to another. It is a navigation control and displays the map of the
site related to its web pages.
Add the following WebForm files,
1. AboutUs.aspx
2. ContactUs.aspx
3. Furnitures.aspx
4. Home.aspx
5. PlasticItems.aspx
6. ProductGroups.aspx

1. Add Sitemap file. Right click on Project and select,

Figure 10: Sitemap file

2. Double on Web.sitemap file type the following code:


1. <?xmlversionxmlversion="1.0"encoding="utf-8" ?>
2. <siteMapxmlnssiteMapxmlns="http://schemas.microsoft.com/AspNet/Site
Map-File-1.0">
3.
4. <siteMapNodeurlsiteMapNodeurl="Home.aspx" title="Home" descriptio
n="Home Page">
5.
6. <siteMapNodeurlsiteMapNodeurl="ProductGroups.aspx" title="Produ
ct Group" description="Product Group Page">
7. <siteMapNodeurlsiteMapNodeurl="Furnitures.aspx" title="Furnitur
es" description="Furniture Items Page" />

Department of Information Technology 122


Government College of Engineering, Karad AST Lab II

8. <siteMapNodeurlsiteMapNodeurl="PlasticItems.aspx" title="Plastic
s" description="Plastic Items Page" />
9. </siteMapNode>
10.
11. <siteMapNodeurlsiteMapNodeurl="Aboutus.aspx" title="About Us"
description="About Us Page" />
12. <siteMapNodeurlsiteMapNodeurl="Contactus.aspx" title="Contact
Us" description="Contact Us Page" />
13.
14. </siteMapNode>
15. </siteMap>

3. Explanation of Web.sitemap code


Web.sitemap is XML base file.
In this file there is one main SiteMapNode that is HOME - Home.aspx. Under that we
have the following two sections :

1. ProductGroup section -- (ProductGroups.aspx) having following child link:


a. Furniture.aspx
b. PlasticItems.aspx

2. Two Independent Page.


a. AboutUs.aspx
b. ContactUs.apx

4. Now, Drag and Drop the SiteMapPath control from ToolBox inside Navigation
group,
Inside following files,
1. AboutUs.aspx
2. ContactUs.aspx
3. Furnitures.aspx
4. Home.aspx
5. PlasticItems.aspx
6. ProductGroups.aspx

Department of Information Technology 123


Government College of Engineering, Karad AST Lab II

5. Write some sample text in every page:


PAGE NAME SAMPLE TEXT
AboutUs.aspx : This is About Us detail page.

ContactUs.aspx This is Contact Us detail page.

Furnitures.aspx This is Furnituresdetail page.

Home.aspx This is Home detail page.

PlasticItems.aspx This is Plastic Items detail page.

ProductGroups.aspx This is Product Groups detail page.

6. Now run application. Type Furniture.aspx in address bar.

Figure 11: Run application

Questions:
1. What is selector in CSS? Explain various types CSS selectors.
2. Explain TreeView control in ASP.NET.
3. How to create and use external style sheet using visual studio developer?

Conclusion : Thus, I have studied themes and master pages with Site-Map and use of CSS.

Department of Information Technology 124


Government College of Engineering, Karad AST Lab II

EXPERIMENT NO. 11

Title: Implement the concept of state management in a web application. Study of


ASP.NET administration and configuration tool.

Outcome: Students will be able to understand state management in ASP.net.

Theory:
ASP.NET WebForms is an abstraction that was built on top of HTTP, but it was
primarily designed as an easy path for Developers from the Visual Basic world to migrate
to the web world. So it mimicked things like Controls, events, event handlers and even
State. ASP.NET provides a number of ways to preserve the state/data between round
trips. In this article, we will briefly explore some of these ways. Data can be maintained
between round trips at two different locations. Yes you guessed it right – on the Client
Side or the Server Side. Take a look at the following diagram which shows different
options for maintaining the state on client as well as the server-

Figure 1: Asp.net State Mangement

Taking an informed decision of storing what kind of data where, is a crucial part of each
web application design. Usually non-secure information is stored at client side and
secured information is always stored at the server side.

 Client Side State Management

Client-side management techniques don’t utilize server resources. They are less secure
but fast performing. Let’s explore some client-side techniques to save state:

 ViewState - ViewState is ASP.NET’s own integrated state serialization mechanism.


ViewState objects are used to store page related data which are preserved between the
round trips from client to server and server to client. View state is maintained as a
hidden field in the page. Here’s how viewstate for an ASP.NET textbox would look

Department of Information Technology 125


Government College of Engineering, Karad AST Lab II

like if you view the page source:

<input type=""hidden"" id="" VIEWSTATE"" name=""


VIEWSTATE"" value=""dDw3GTg2NTI5MDEDC0y3="">

Let’s see ViewState in action with an example. Design a simple web form and add
a button on the web form. Write the following code in the code behind of the web form

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
ViewState["PageHitCounter"] = 0;
}
}
protected void btnPageHitCounter_Click(object sender, EventArgs e)
{
ViewState["PageHitCounter"] = Convert.ToInt32(ViewState["PageHitCounter"]) + 1;
Response.Write("The number of postbacks are - " +
ViewState["PageHitCounter"].ToString());
}

This code shows how many times the page has been posted back to the server.
Now normally with every rountrip the PageHitCounter would be reset to 0, but
since we are using ViewState, the counter gets preserved between round trips.

 Query String - Query String is passed in the URL. They store the value in
the form of Key-Value pair. You will have to maintain the Query Strings
when you pass it from one page to second page and second page to the third
page.
For example, when redirecting a request from one page to another page, you can pass
the Query String as shown here –
Response.Redirect("menu.aspx?category=vegfood");

Query string is limited to simple string information, and they’re easily accessible and
readable.

Department of Information Technology 126


Government College of Engineering, Karad AST Lab II

 Hidden Fields - Hidden Fields are similar to a text box but does not get
displayed on the UI. However you can see the value of hidden fields when you
view page source in the browser. Using Hidden Fields, you can pass
information from one page to another page without the end user's knowledge,
primarily for internal processing.
Drag and Drop a hiddenfield control on the web page from the Visual Studio toolbox
and set its value in the Page Load event as shown below -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
siteReference.Value = "http://www.dotnetcurry.com";
}
}
Run the page and check the source code. You will see the Hidden Field value as shown
below -

 Cookies - Cookies are small files that are created in the web browser’s memory or
on the client’s hard disk. The maximum size of a cookie file is 4 KB. You can
create two types of cookies. Transient Cookie (memory) and Persistent Cookie
(hard disk). Transient Cookies are accessible till the time the browser is running.
Persistent Cookies are cookies which have an expiry time. When you don't set
expiry time for the cookie, the cookies are treated as transient cookies.
Cookie contains a Key/Value pair. Cookie can also contain the collection of key/value
pairs. Let's see an example of a Cookie –

Response.Cookies["CityName"].Value = "London";
HttpCookie dncCookie = new HttpCookie("DotNetCurry");
dncCookie.Values["ArticleName"] = "SharePoint 2013 - Business Connectivity Services";
dncCookie.Values["Author"] = "SharePoint Admin";
dncCookie.Values["PublishDate"] = DateTime.Now.AddDays(10).ToLongDateString();
dncCookie.Values["ArticleName"] = "SharePoint 2013 - Business Connectivity
Services"; dncCookie.Expires = DateTime.Now.AddDays(20);
Response.AppendCookie(dncCookie);

Just like query strings, cookies are limited to storing simple strings. Users also disable

Department of Information Technology 127


Government College of Engineering, Karad AST Lab II

cookies or manually delete them which renders them ineffective.


 Server Side State Management

Unlike Client-side state management techniques, Server-side options are more secure
but can become slow to respond, depending on the information that is stored. Since
these techniques directly use the resources of the web server, scalability issues is
something to be considered when storing large amount of data.
ASP.NET provides some options to implement server-side state management:
 Application State - The Application object is an instance of the
System.Web.HttpApplicationState class. You can create Application Level object like
a name/value pair and share it across all users. You can declare Application level
variable when the web application starts. Usually developers declare Application
Level variables in Global.asax file. The Global.asax file contains events
(Application_Start Event, Application_End Event and Application_Error Event)
which get associated with Application object.
You can declare Application level objects in the Application_Start event. Let's see an
example –
Add a Global.asax file in your web application and write the following code in the
Application_Start event -

void Application_Start(object sender, EventArgs e)


{
Application["CopyRightNote"] = "DotNetCurry CopyRight 2013-2014";
Application["HitCounter"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["HitCounter"] =Convert.ToInt32(Application["HitCounter"]) + 1;
Application.Lock();
}
Now you can access both application variables on any page.

 Session State – Session objects are stored on the server side and are an instance of
the System.Web.SessionState.HttpSessionState class. It can be used to store any type
of data in the memory. They are primarily used for storing user specific information
like shopping cart, preferences etc and is never transferred to the client. You can
declare session level variables in the following manner -
Session["AccountNo"] = 1998773887324556;
By default sessions are stored in server memory called as In-Process. You can also store
session as out-of-process. You can store the session information in Microsoft SQL Server

Department of Information Technology 128


Government College of Engineering, Karad AST Lab II

or State Server. Session state must be used thoughtfully as it leads to scalability issues if
misused.

 Cache - The Cache object is an instance of the System.Web.Caching.Cache


class. Cache is stored on the server side and is more scalable in nature, as ASP.NET
removes objects if the memory becomes scarce. This also makes it unreliable in some
cases. Cache objects can have expiration polices set on them and is shared across
users. You can implement Page Caching and Data Caching. Let's see a small example
of both.

 Page Caching -

 Data Caching -

Cache.Insert("CacheDateTime", DateTime.Now);
You can also cache client-side by using the Location=”Client” option.

 Profile - Profile data is stored in the SQL Server database by default. This database
structure is preset, so if you want any custom user details to be stored, you will need
to create a custom database and write a custom provider for it. Profiles are designed
to store information permanently. Here’s a simple example of using profiles:
<profile>
<properties>
<add name=""FirstName"" type=""System.String"/">
<add name=""LastName"" type=""System.String"/">
<add name=""Address"" type=""System.String"/">
<add name=""City"" type=""System.String"/">
<add name=""Age"" type=""System.Int32"/">
</add></add></add></add></add></properties>
</profile>

Using the profile properties in your application -

Profile.FirstName = "John";
Profile.LastName = "Mark";
Profile.City = "London";
Profile.Age = 46;
The Profile object provides you with a persistent form of session state that is strongly
typed.

Department of Information Technology 129


Government College of Engineering, Karad AST Lab II

 Context.Items - The HttpContext object is provided by the Page.Context property.


The HttpContext.Items collection can be used to temporarily store data across
postback. View state and session state can be used for a similar effect, but they
assume longer-term storage. Context can be used for storing data for one request
only. We can store it as a key/value pair as shown below -
Context.Items["SocialPinNo"] = 3666736;
Response.Write(Context.Items["SocialPinNo"].ToString());

Questions:

1. What is ViewState? How it works in ASP.NET?


2. What are cookies? Explain various properties of HttpCookie class

Conclusion : Thus, I have studied the state management in ASP.net.

Department of Information Technology 130


Government College of Engineering, Karad AST Lab II

EXPERIMENT NO. 12

Title: Using Database controls make a login application with registration.

Outcome: Students will be able to use database controls to make a login application
with registration in ASP.net.

Theory:

Login Application :

Create 2 web forms here: one for login page design and other to show the welcome message.
On the login page, the user will enter its username and password. This information will be
sent in form of a SQL Query to the database. Based on the query results, appropriate actions
will be taken. The 3 major steps in this process are:
 Creating the database
 Modifying the web.config file, and
 The code to validate the user information.
techwareguide.aspx: Design code of the login web form.
techwareguide.aspx.cs: Code that works on the login page to validate user info from the
database.
techwareLogin.aspx: Design code of the page that will appear to the authenticated users.
techwareLogin.aspx.cs: No code required. Leave it untouched.
web.config (auto-generated): In this file, you have to specify the database connection string,
in order to connect with database and validate user credentials. No need to create this file as it
is already created by default when you will create the ASP.NET website project.
 SQL Server database: In the database, create a table called “UserInformation” and
store user credentials in it.
Step 1: Create SQL Server Database:
 To add SQL database to your ASP.NET website, press “Control+Shift+A” hotkey and
then choose to add a SQL Server Database.
 You can manage your database from the Server Explorer. In case, it’s not visible then
toggle it from the View menu. From the Server Explorer, choose to create a new table
to store the user credentials. I created a table named UserInformation with
field Usernameand Password. Create a similar type of table and insert some dummy
data in it.

Department of Information Technology 131


Government College of Engineering, Karad AST Lab II

Step 2: Configure Web.config File:


In this step, you need to add the database connection string in Web.config file. Follow these
steps to do it successfully:
 From the Server Explorer, right-click on the database file and select “Properties“. See
the screenshot below for reference.

Figure 1: Server Explorer


 Now, from the Properties window, copy the data of “Connection String“, as shown
below.

Figure 2: Connection String


Open Web.config file from the Solution Explorer and add the <connectionStrings> tag
and paste the connection string, as you can see in the code snippet added below.
web.config:

<configuration>

<system.web>

<compilation debug="true" targetFramework="4.5.2" />

<httpRuntime targetFramework="4.5.2" />

</system.web>

<connectionStrings>

Department of Information Technology 132


Government College of Engineering, Karad AST Lab II

<add name="dbconnection" connectionString="Paste Database Connection String Here!"/>


</connectionStrings>

</configuration>

Step 3: Create ASP.NET Login page using C#:


To create a new website project, go to “File>New Web Site…” and select “ASP.NET
Empty Web Site“. Now, add a web form to design the login page controls and another one to
display the welcome message.

Figure 3: Login Page


Now, double tap on the button (like login button visible in screenshot above) that will
implement the login code in the login page CS (C#) file. This is really simple. First, add the 3
namespaces specified below.
 using System.Configuration;
 using System.Data;
 using System.Data.SqlClient;
techwareguide.aspx.cs:

protected void button1_Click(object sender, EventArgs e)

SqlConnection con = new


SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);

con.Open();

SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName =@username and
Password=@password", con);

cmd.Parameters.AddWithValue("@username", textBox1.Text);

cmd.Parameters.AddWithValue("@password", textBox2.Text);

Department of Information Technology 133


Government College of Engineering, Karad AST Lab II

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataTable dt = new DataTable();

da.Fill(dt);

if (dt.Rows.Count > 0)

Response.Redirect("Name of the webpage that validated user can access");

else

Label3.Visible = true;
Label3.Text = "Wrong Details";
}
}

Figure 4: Web application Output

Registration Process:
Users will enter their details in the user registration form and hit the Register button. After
that, a connection to the database will be established and a SQL Insert query will be executed
to store all user inputs in the user details table.
Here is the breakdown of the complete process:
1. Creating an empty ASP.NET website.
2. Designing the user registration form.

Department of Information Technology 134


Government College of Engineering, Karad AST Lab II

Figure 5: Registration Form


3. Adding a SQL database to the project in which we will create a table to store user details.
Step 1: Hit the Control+Shift+A shortcut and select SQL Server Database option. This will
prompt you to create an App_Data folder within your project, accept it and open Server
Explorer box. Now, you have added a database to your ASP.NET website.
Step 2: From the Server Explorer, right click on the Tables and select the Add New Table
option, as shown in the screenshot below.

Figure 6: Add new table in Database

Step 3: Now, you will see the table designing interface, as shown below.

Department of Information Technology 135


Government College of Engineering, Karad AST Lab II

Figure 7: Table design interface


Simply specify the user attributes and their respective data types that you want to store within
the table. After that, click on the Update button. This will generate a script to update the
database, as shown below. Now, click on the Update Database button to create your table.

Figure 8: Update database


4. Configuring web.config file.
Open Web.config file from the Solution Explorer and paste the connection string of your
database in the following format within the <configuration></configuration> tags. Do not
add the <connectionStrings> tag inside any other tag.

<connectionStrings>

<add name="dbconnection" connectionString="Paste your DB connection string here"/>

</connectionStrings>

To get the connectionString of your database, open Server Explorer and right click on it.
Select the Properties option. Now, from the Properties box, copy the Connection String of
your database and paste it at the specified place in the code snippet.

Department of Information Technology 136


Government College of Engineering, Karad AST Lab II

5. Code the backend of user registration form.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into RegistrationTable values (@FirstName, @LastName,
@Email, @MobileNumber, @Password)", con);

cmd.Parameters.AddWithValue("FirstName", FnameTxt.Text);
cmd.Parameters.AddWithValue("LastName", LnameTxt.Text);
cmd.Parameters.AddWithValue("Email", Email.Text);
cmd.Parameters.AddWithValue("MobileNumber", MobileNumber.Text);
cmd.Parameters.AddWithValue("Password", Password.Text );
cmd.ExecuteNonQuery();
Label7.Visible = true;
Label7.Text = "User registered successfully";

FnameTxt.Text = "";
LnameTxt.Text = "";
Email.Text = "";

Department of Information Technology 137


Government College of Engineering, Karad AST Lab II

MobileNumber.Text = "";
Password.Text = "";
FnameTxt.Focus();
}
}

6. Try and test the application.


Debug your ASP.NET site and enter the details in the user registration form, as shown in the
main screenshot. After that, click on the Register button. If you get any SQL Exception in
Visual Studio, then probably check out the table or the C# code. And if everything goes
perfect, you will see this message ‘User registered successfully’. You can also check if the
code worked or not from the user details table data, as shown below.

Figure 9: Test Application

Questions:
1. What is the difference between ExecuteScalar and ExecuteNonQuery?
2. What is ADO.NET?
3. Why is it important to close an ADO.NET application?
4. What is DataAdapter?

Conclusion : Thus, I have created login application with registration from ASP.NET

Department of Information Technology 138


Government College of Engineering, Karad AST Lab II

EXPERIMENT NO. 13

Title: Use Dataset, DataReader, XML Reader and Data Sources (SQL, Object and XML)
with any windows or web application.

Outcome: Students will be able to understand use of Dataset, DataReader, XML Reader
and Data Sources (SQL, Object and XML) with web application in ASP.NET

Theory:
Learning ADO.NET objects
ADO.Net provides a bridge between the front end controls and the back end
database. The ADO.Net objects encapsulate all the data access operations and the
controls interact with these objects to display data, thus hiding the details of
movement of data. The following figure shows the ADO.Net objects at a glance:

Figure 1: ADO.NET objects


 The DataSet Class:
The data set represents a subset of the database. It does not have a continuous
connection to the database. To update the database a reconnection is required. The
DataSet contains DataTable objects and DataRelation objects. The DataRelation objects
represent the relationship between two tables.

Following table shows some important properties of the DataSet class:

Department of Information Technology 139


Government College of Engineering, Karad AST Lab II

Properties Description
CaseSensitive Indicates whether string comparisons within the data tables
are casesensitive.

Container Gets the container for the component.


DataSetName Gets or sets the name of the current data set.
DefaultViewManager Returns a view of data in the data set.
DesignMode Indicates whether the component is currently in design mode.
EnforceConstraints Indicates whether constraint rules are followed when attempting
any update operation.

Events Gets the list of event handlers that are attached to this component.

ExtendedProperties Gets the collection of customized user information associated


with the DataSet.

HasErrors Indicates if there are any errors.

IsInitialized Indicates whether the DataSet is initialized

Locale Gets or sets the locale information used to compare strings


within the table.

Namespace Gets or sets the namespace of the DataSet.

Prefix Gets or sets an XML prefix that aliases the namespace of the
DataSet.
Relations Returns the collection of DataRelation objects

Tables Returns the collection of DataTable objects.

Following table shows some important methods of the DataSet class:

Methods Description
AcceptChanges Accepts all changes made since the DataSet was loaded or this
method was called.

Department of Information Technology 140


Government College of Engineering, Karad AST Lab II

BeginInit Begins the initialization of the DataSet. The initialization


occurs at run time.
Clear Clears data.
Clone Copies the structure of the DataSet, including all DataTable
schemas, relations, and constraints. Does not copy any data.
Copy Copies both the structure and data.
CreateDataReader() Returns a DataTableReader with one result set per DataTable, in
the same sequence as the tables appear in the Tables collection.

CreateDataReader(DataTable[]) Returns a DataTableReader with one result set per DataTable.


EndInit Ends the initialization of the data set.
Equals(Object) Determines whether the specified Object is equal to the current
Object.
Finalize Free resources and perform other cleanups.
GetChanges Returns a copy of the DataSet with all changes made since it
was loaded or the AcceptChanges method was called.
GetChanges(DataRowState) Gets a copy of DataSet with all changes made since it was
loaded or the AcceptChanges method was called, filtered by
DataRowState.

GetDataSetSchema Gets a copy of XmlSchemaSet for the DataSet.


GetObjectData Populates a serialization information object with the data
needed to serialize the DataSet.
GetType Gets the Type of the current instance.
GetXML Returns the XML representation of the data.
GetXMLSchema Returns the XSD schema for the XML representation of the
data.
HasChanges() Gets a value indicating whether the DataSet has changes,
including new, deleted, or modified rows.
HasChanges(DataRowState) Gets a value indicating whether the DataSet has changes,
including new, deleted, or modified rows, filtered by
DataRowState.

IsBinarySerialized Inspects the format of the serialized representation of the

DataSet.
Load(IDataReader, Fills a DataSet with values from a data source using the supplied
LoadOption, IDataReader, using an array of DataTable instances to supply the
DataTable[]) schema and namespace information.

Department of Information Technology 141


Government College of Engineering, Karad AST Lab II

Load(IDataReader, Fills a DataSet with values from a data source using the supplied
LoadOption, IDataReader, using an array of strings to supply the names for
String[]) the tables within the DataSet
Merge() Merges the data with data from another DataSet. This method
has different overloaded forms.
ReadXML() Reads an XML schema and data into the DataSet. This method
has different overloaded forms
ReadXMLSchema() Reads an XML schema into the DataSet. This method has
different overloaded forms
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
WriteXML() Writes an XML schema and data from the DataSet. This
method has different overloaded forms.
WriteXMLSchema() Writes the structure of the DataSet as an XML schema. This
method has different overloaded forms.

 The DataAdapter Object


The DataAdapter object acts as a mediator between the DataSet object and the database.
This helps the Dataset to contain data from multiple databases or other data source.
 The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter combination.
This object provides a connection oriented access to the data records in the database.
These objects are suitable for read-only access, such as populating a list and then
breaking the connection.
 DbCommand and DbConnection Objects
The DbConnection object represents a connection to the data source. The connection
could be shared among different command objects.
The DbCommand object represents the command or a stored procedure sent to
the database from retrieving or manipulating data.
Example:
So far, we have used tables and databases already existing in our computer. In
this example, we will create a table, add column, rows and data into it and display the
table using a GridView object.
The source file code is as given:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="createdatabase._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

Department of Information Technology 142


Government College of Engineering, Karad AST Lab II

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

The code behind file is as given:


namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource = ds.Tables["Student"];
GridView1.DataBind();
}
}
private DataSet CreateDataSet()
{
//creating a DataSet object for tables DataSet
dataset = new DataSet();

Department of Information Technology 143


Government College of Engineering, Karad AST Lab II

// creating the student table


DataTable Students = CreateStudentTable();
dataset.Tables.Add(Students);
return dataset;
}

private DataTable CreateStudentTable()


{

DataTable Students = new DataTable("Student");

// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");

// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");
AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
AddNewRow(Students, 1, "Rajat Mishra", "Patna");

return Students;
}

private void AddNewColumn(DataTable table, string columnType, string


columnName)
{
DataColumn column = table.Columns.Add(columnName,
Type.GetType(columnType));
}

//adding data into the table


private void AddNewRow(DataTable table, int id, string name, string city)

Department of Information Technology 144


Government College of Engineering, Karad AST Lab II

{
DataRow newrow = table.NewRow();
newrow["StudentID"] = id;
newrow["StudentName"] = name;
newrow["StudentCity"] = city;
table.Rows.Add(newrow);
}
}
}

When you execute the program, observe the following:


 The application first creates a data set and binds it with the grid view control
using the DataBind() method of the GridView control.
 The Createdataset() method is a user defined function, which creates a new
DataSet object and then calls another user defined method CreateStudentTable()
to create the table and add it to the Tables collection of the data set.
 The CreateStudentTable() method calls the user defined methods
AddNewColumn() and AddNewRow() to create the columns and rows of the
table as well as to add data to the rows.
When the page is executed, it returns the rows of the table as shown:

Figure 2: Table
 Data Sources
A data source control interacts with the data-bound controls and hides the complex
data binding processes. These are the tools that provide data to the data bound
controls and support execution of operations like insertions, deletions, sorting, and
updates.
Each data source control wraps a particular data provider-relational databases,
XML documents, or custom classes and helps in:
 Managing connection

Department of Information Technology 145


Government College of Engineering, Karad AST Lab II

 Selecting data
 Managing presentation aspects like paging, caching, etc.
 Manipulating data
There are many data source controls available in ASP.NET for accessing data from
SQL Server, from ODBC or OLE DB servers, from XML files, and from business
objects.
Based on type of data, these controls could be divided into two categories:
 Hierarchical data source controls
 Table-based data source controls
The data source controls used for hierarchical data are:
 XMLDataSource - It allows binding to XML files and strings with or
without schema information.
 SiteMapDataSource - It allows binding to a provider that supplies site
map information.
The data source controls used for tabular data are:
Data source controls Description

SqlDataSource It represents a connection to an ADO.NET data provider that

returns SQL data, including data sources accessible via OLEDB


and ODBC.

ObjectDataSource It allows binding to a custom .Net business object that returns


data.

LinqdataSource It allows binding to the results of a Linq-to-SQL query (supported


by ASP.NET 3.5 only).

AccessDataSource It represents connection to a Microsoft Access database.

 Data Source Views


Data source views are objects of the DataSourceView class. Which represent a
customized view of data for different data operations such as sorting, filtering, etc.
The DataSourceView class serves as the base class for all data source view classes,
which define the capabilities of data source controls.
The following table provides the properties of the DataSourceView class:

Department of Information Technology 146


Government College of Engineering, Karad AST Lab II

Properties Description

CanDelete Indicates whether deletion is allowed on the underlying data


source.

CanInsert Indicates whether insertion is allowed on the underlying


data source.

CanPage Indicates whether paging is allowed on the underlying data


source.

CanRetrieveTotalRowCount Indicates whether total row count information is available.

CanSort Indicates whether the data could be sorted.

CanUpdate Indicates whether updates are allowed on the underlying


data source.

Events Gets a list of event-handler delegates for the data source


view.

Name Name of the view.

The following table provides the methods of the DataSourceView class:

Methods Description

CanExecute Determines whether the specified command can be


executed.

ExecuteCommand Executes the specific command.

ExecuteDelete Performs a delete operation on the list of data that the


DataSourceView object represents.

ExecuteInsert Performs an insert operation on the list of data that


the DataSourceView object represents.

ExecuteSelect Gets a list of data from the underlying data storage.

ExecuteUpdate Performs an update operation on the list of data that


the DataSourceView object represents.

Delete Performs a delete operation on the data associated


with the view.

Insert Performs an insert operation on the data associated


with the view.

Department of Information Technology 147


Government College of Engineering, Karad AST Lab II

Select Returns the queried data.

Update Performs an update operation on the data associated


with the view.

OnDataSourceViewChanged Raises the DataSourceViewChanged event.

RaiseUnsupportedCapabilitiesError Called by the RaiseUnsupportedCapabilitiesError


method to compare the capabilities requested for an
ExecuteSelect operation against those that the view
supports.

 The SqlDataSource Control


The SqlDataSource control represents a connection to a relational database such as
SQL Server or Oracle database, or data accessible through OLEDB or Open
Database Connectivity (ODBC). Connection to data is made through two
important properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax of the control:

<asp:SqlDataSource runat="server" ID="MySqlSource"


ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />

<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource" />

Configuring various data operations on the underlying data depends upon the
various properties (property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource
control, which provides the programming interface of the control:

Property Group Description

DeleteCommand, Gets or sets the SQL statement, parameters, and type for
DeleteParameters, deleting rows in the underlying data.
DeleteCommandType

FilterExpression, Gets or sets the data filtering string and parameters.


FilterParameters

Department of Information Technology 148


Government College of Engineering, Karad AST Lab II

InsertCommand, Gets or sets the SQL statement, parameters, and type for
InsertParameters, inserting rows in the underlying database.
InsertCommandType

SelectCommand, Gets or sets the SQL statement, parameters, and type for
SelectParameters, retrieving rows from the underlying database.
SelectCommandType

SortParameterName Gets or sets the name of an input parameter that the


command's stored procedure will use to sort data.

UpdateCommand, Gets or sets the SQL statement, parameters, and type for
UpdateParameters, updating rows in the underlying data store.
UpdateCommandType

The following code snippet shows a data source control enabled for data manipulation:

<asp:SqlDataSource runat="server" ID= "MySqlSource"


ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"

UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"


DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"

FilterExpression= "EMPLOYEEID > 10">


.....
.....
</asp:SqlDataSource>

 The ObjectDataSource Control


The ObjectDataSource Control enables user-defined classes to associate the output
of their methods to data bound controls. The programming interface of this class is
almost same as the SqlDataSource control.
Following are two important aspects of binding business objects:
 The bindable class should have a default constructor, it should be stateless,
and have methods that can be mapped to select, update, insert, and delete
semantics.
 The object must update one item at a time, batch operations are not supported.
Let us go directly to an example to work with this control. The student class is the

Department of Information Technology 149


Government College of Engineering, Karad AST Lab II

class to be used with an object data source. This class has three properties: a student id,
name, and city. It has a default constructor and a GetStudents method for retrieving
data.
The student class:

public class Student

public int StudentID { get; set; }

public string Name { get; set; }

public string City { get; set; }

public Student()

{}

public DataSet GetStudents()

dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });


DataSet ds = new DataSet();
dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });

ds.Tables.Add(dt);
DataTable dt = new DataTable("Students");

dt.Columns.Add("StudentID",
return ds; typeof(System.Int32));

dt.Columns.Add("StudentName", typeof(System.String));

}dt.Columns.Add("StudentCity", typeof(System.String));
Take the following steps to bind the object with an object data source and retrieve
data:
}
 Create a new web site.
 Add a class (Students.cs) to it by right clicking the project from the
Solution Explorer, adding a class template, and placing the above code in it.

Department of Information Technology 150


Government College of Engineering, Karad AST Lab II

 Build the solution so that the application can use the reference to the class.
 Place an object data source control in the web form.
 Configure the data source by selecting the object.

Figure 3: Choose Business Object


 Select a data method(s) for different operations on data. In this example, there is
only one method.

Figure 4: Select a data method(s) for different operations


 Place a data bound control such as grid view on the page and select the object
data source as its underlying data source.

Figure 5: Place a data bound control such as grid view on the page

Department of Information Technology 151


Government College of Engineering, Karad AST Lab II

 At this stage, the design view should look like the following:

Figure 6: Design view


 Run the project, it retrieves the hard coded tuples from the students class.

Figure 7: Output

 The AccessDataSource Control


The AccessDataSource control represents a connection to an Access database. It is
based on the SqlDataSource control and provides simpler programming interface.
The following code snippet provides the basic syntax for the data source:

<asp:AccessDataSource ID="AccessDataSource1 runat="server"

DataFile="~/App_Data/ASPDotNetStepByStep.mdb" SelectCommand="SELECT *
FROM [DotNetReferences]">

</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it
can also be used for performing insert, update, or delete operations. This is done
using the ADO.NET commands and parameter collection.
Updates are problematic for Access databases from within an ASP.NET application
because an Access database is a plain file and the default account of the
ASP.NET application might not have the permission to write to the database file.

Department of Information Technology 152


Government College of Engineering, Karad AST Lab II

Questions:
1. What is Use of DataSet object in ADO.NET?
2. What is the difference between DataSet and DataReader?
3. Explain the clear() method of DataSet?
4. What is disconnected data?

Conclusion : Thus, I have studied accessing database using Dataset and Data Sources in
ASP.Net

Department of Information Technology 153

You might also like