Professional Documents
Culture Documents
AST II Lab Manual Content
AST II Lab Manual Content
Experiment No 1
Title: - Installation of Android SDK, emulator, creating simple project and study of android
project structure.
Theory:-
1. Introduction
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.
We need to install both the "Android Studio", which is an IDE based on IntelliJ (a
popular Java IDE); and "Android SDK" libraries.
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".
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 installation installed basic SDK packages. You may need to add a few more to
run the Hello-world.
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
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.
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
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) 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.
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.
Folder structure in the newly created project in Project mode would look like below.
.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.
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.
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.
This folder contains the actual android code and resource files. Below image clearly depicts
the folder structure.
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.
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:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
... />
<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"
... />
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.
Within the Activity that hosts this layout, the following method handles the click event:
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.
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.
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" />
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.
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.
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.
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.
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.
<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:
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.
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.
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.
Within the Activity that hosts this layout, the following method handles the click event for
both checkboxes:
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.
Toggle buttons
Conclusion :- Thus, I have implemented Buttons, Text Fields, Checkboxes, Radio Buttons,
and Toggle Buttons with their events handler.
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
ArrayList<PendingIntent> deliveryIntents)
Send a multi-part 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.
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;
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 {
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;
}
}
}
}
}
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"
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>
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
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
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.
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
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.
6 Run the application to launch Android emulator and verify the result of the changes
done in the application.
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);
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;
}
}
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>
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.
Fig 3: My Application
Now use Compose SMS button to launch Android built-in SMS clients which is shown
below −
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.
constants.
6 Run the application to launch Android emulator and verify the result of the changes
done in the application.
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);
}
});
}
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 −
Experiment No 4
Title: - Write a program to study and demonstrate Broadcast Receiver.
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.
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>
There are several system generated events defined as final static fields in theIntent class.
The following table lists a few important system events.
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.
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.
<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">
</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.
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
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 {
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:
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>
<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"
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
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 −
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.
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:
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:
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).
When the user selects an item from the drop-down, the Spinner object receives an on-item-
selected event.
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
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
Example:
@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);
See the TimePickerDialog class for information about the constructor arguments.
Now all you need is an event that adds an instance of this fragment to your activity.
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:
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.
Here's an example:
@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);
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.
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:
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:
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.
You can also chain your methods and avoid holding on to the Toast object, like this:
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.
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"
/>
</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:
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().
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:
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:
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.
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:
@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.
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.
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.
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:
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.
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>
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.
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
android: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.
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:
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
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."
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.
@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.
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).
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.
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().
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.
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).
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
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.
For views that provide contextual actions, you should usually invoke the contextual action
mode upon one of two events (or both):
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 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.
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:
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
@Override
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;
}
}
});
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:
For example:
@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;
}
}
@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.
Experiment No 7
Title: - Write a program 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.
In supported launchers and on devices running Android 8.0 (API level 26) and higher:
Users can also long-press on an app icon to glance at the notifications associated with a
notification badge.
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
Lights
Vibration
Show on lockscreen
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.
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.
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);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
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.
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:
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.
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.
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().
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
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 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);
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.
For example, the following code snippet demonstrates how to alter the notification created in
the previous snippet to use the expanded layout:
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.
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
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(
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.
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:
.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.
.setLabel(replyLabel)
.build();
The system prompts the user to input a response when they trigger the notification action.
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:
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();
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
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.
Experiment No 8
Title: - Write a program to study and use of SQLite database.
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
Apart from this , there are other functions available in the database package , that does this
job. They are listed below
Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below
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
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.
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.
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
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.
4 Create a new Activity as DisplayContact.java that will display the contact on the screen
10 Run the application and choose a running android device and install the application on it and verify the
results.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
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);
switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
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;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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);
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
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);
}
}
}
@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;
}
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
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 d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
}
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;
@Override
public void onCreate(SQLiteDatabase db) {
@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;
}
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;
}
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
<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"
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>
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"
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
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"
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>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
</menu>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>
</menu>
<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.
Click on the add button of the menu screen to add a new contact. It will display the
following screen −
EXPERIMENT NO 9
Title: Implement web application using ASP.NET with web control and provide input
validations using input valuators.
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 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
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
</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 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
Operator it specifies the comparison operator, the available values are: Equal,
NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual
and DataTypeCheck
The RegularExpressionValidator
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
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 CustomValidator:
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.
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:
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.
A sub folder named Theme1 is automatically created inside the APP_Themes folder in the
SolutionExplorer.
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.
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),
CSS Code
1. #header{
2. color: #247BA0;
3. text-align: center;
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;
48. text-align:center;
49. padding-bottom: 5%;
50. font-size: 20px;
51. }
52. #con{
53. border:double;
54. }
55.
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
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>
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
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.
EXPERIMENT NO. 11
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-
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 management techniques don’t utilize server resources. They are less secure
but fast performing. Let’s explore some client-side techniques to save state:
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
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.
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
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 -
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
or State Server. Session state must be used thoughtfully as it leads to scalability issues if
misused.
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>
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.
Questions:
EXPERIMENT NO. 12
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.
<configuration>
<system.web>
</system.web>
<connectionStrings>
</configuration>
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);
da.Fill(dt);
if (dt.Rows.Count > 0)
else
Label3.Visible = true;
Label3.Text = "Wrong Details";
}
}
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.
Step 3: Now, you will see the table designing interface, as shown below.
<connectionStrings>
</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.
}
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 = "";
MobileNumber.Text = "";
Password.Text = "";
FnameTxt.Focus();
}
}
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
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:
Properties Description
CaseSensitive Indicates whether string comparisons within the data tables
are casesensitive.
Events Gets the list of event handlers that are attached to this component.
Prefix Gets or sets an XML prefix that aliases the namespace of the
DataSet.
Relations Returns the collection of DataRelation objects
Methods Description
AcceptChanges Accepts all changes made since the DataSet was loaded or this
method was called.
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.
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.
"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>
// 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;
}
{
DataRow newrow = table.NewRow();
newrow["StudentID"] = id;
newrow["StudentName"] = name;
newrow["StudentCity"] = city;
table.Rows.Add(newrow);
}
}
}
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
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
Properties Description
Methods Description
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:
DeleteCommand, Gets or sets the SQL statement, parameters, and type for
DeleteParameters, deleting rows in the underlying data.
DeleteCommandType
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
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:
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 Student()
{}
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.
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 5: Place a data bound control such as grid view on the page
At this stage, the design view should look like the following:
Figure 7: Output
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.
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