Iot Lab Manual For Print
Iot Lab Manual For Print
INTERNET OF THINGS
B.Tech- I Year
CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(UGC AUTONOMOUS COLLEGE, ACCREDITED BY NAAC WITH “A” GRADE)
Lab Manual
INTERNET OF THINGS
B.Tech- I Year
3. To Implement Data and Knowledge Management and use of Devices in IoT Technology.
DEFINITION OF IOT:
The Internet of Things (IoT) is a network comprised of physical objects capable of gathering and
sharing electronic information
(OR)
The internet of things (IoT) is a computing concept that describes the idea of everyday physical
objects being connected to the internet and being able to identify themselves to other devices
HISTORY OF IOT:
The term Internet of Things is 16 years old. But the actual idea of connected devices had been
around longer, at least since the 70s. Back then, the idea was often called “embedded internet” or
“pervasive computing”.
Figure1. Internet of things
The term “Internet of Things” was coined by Kevin Ashton in 1999 during his work at Procter &
Gamble. Ashton who was working in supply chain optimization, wanted to attract senior
management’s attention to a new exciting technology called RFID. Because the internet was the
hottest new trend in 1999 and because it somehow made sense, he called his presentation “Internet
of Things”. Even though Kevin grabbed the interest of some P&G executives, the term Internet of
Things did not get widespread attention for the next 10 years.
IOT ARCHITECTURE:
IOT architecture consists of different layers of technologies supporting IOT. It serves to illustrate
how various technologies relate to each other and to communicate the scalability, modularity and
configuration of IOT deployments in different scenarios
Figure3.IoTArchitecture
Enabling technologies for the Internet of Things are considered in and can be grouped into
three categories:
1. Technologies that enable “things” to acquire contextual information,
2. Technologies that enable “things” to process contextual information, and
3. Technologies to improve security and privacy.
Connectivity
Dynamic Nature
Enormous scale
Sensing
Heterogeneity
Security
BENEFITS OF IOT:
1. Data Management: Using devices we collect lots of raw data. These data are filtered
and managed by the IOT systems to produce an informative data. IOT reduces the
overall complexity of data management.
2. Good Decision Making: More informative data will help you to take right decision.
Calculated charts and reports generated by the IOT systems will help you to take good
decisions for your businesses.
3. Tracking and Safety: Using IOT system we can track and monitor all the objects
functionalities and their outputs. For safety of life we can track the quality and
expiration date of the products before its consumption.
4. Save Time & Money: IOT system perform task rapidly and doesn't requires human
which makes these devices more cost effective and fast
1. Jumper wires – Jumper wires/cables or simply jumpers are available in various colours with
male-male, female-female or male-female connectors at the two ends, and are used for
interconnecting components on the breadboard or Arduino board.
LEDs consume very low power and so are long-lasting, with little energy wasted in heat. They
are used in flashlights, on front of appliances like TV (to indicate condition, like green for on,
red for standby, etc.).
3. Resistors: These are color-coded (with bands or stripes), and used to control the voltages
and currents in the circuit, e.g., to limit current in LEDs to set light intensity and avoid
damaging the LEDs. Note that unlike an LED, a resistor is reverse (i.e., polarity does not
matter).
Figure7. Potentiometer
5. Diode: A diode is an electronic device with two terminals (wires). It lets current flow in one
direction only (from positive or anode to negative or cathode), and acts like a gate or switch. An
LED is a special type of diode, where reversing the connection will damage the device. Signal
diode handles low currents, whereas power diodes are used with large currents/voltages.
Figure8. Diode
7. Buzzer: It is a piezo element, and produces a sound of a specified tone or frequency. It can also
be used to sense or detect vibrations (e.g., knock or tap).
Figure10 Buzzer
8. Temperature Sensor: When the temperature sensor is connected to a power supply, it produces
a voltage corresponding to the ambient temperature. By reading this voltage with an Arduino, we
can determine the temperature and record it in the computer, etc.
Figure11. LM35
9. DC Motor: DC motors are used in toys, RC cars, robots, and many other situations. By
controlling the voltage given to a motor using the Arduino, we can control the motion (angle
or speed) of the platform (e.g., robot manipulator or mobile robot) to which the motor is
attached.
Figure12. DC Motor
10. Push Button: Push buttons are switches which are used to turn on and off devices like motors,
LEDs, and so on.
11. RC Servo: RC (for radio control) servos are motors used in toy cars, RC planes and boats (to
control fins), etc, generally with less than one full rotation (whereas DC motors rotate
continuously).
Figure14. RC Servo
12. Relays: A relay is a switch that is turned ON and OFF by an electrical signal (e.g., sent
from Arduino). Typically, it used to turn on or off large-current devices (e.g., motors).
Figure15. Relay
13. Breadboard: A breadboard is used to build and test electronic circuits. No soldering is required
so we can change connections and replace components easily. Parts will be available for re-
use afterwards aft er successful testing.
Week 2
2.1. INTRODUCTION TO PYTHON:
It incorporates modules, exceptions, dynamic typing, very high level dynamic data types,
and classes.
It has interfaces to many system calls and libraries, as well as to various window systems,
and is extensible in C or C++.
Finally, Python is portable: it runs on many Unix variants, on the Mac, and on Windows
2000 and later.
Python is ideal language for scripting and rapid application development in many areas on
most platforms.
The Python Software Foundation is an independent non-profit organization that holds the copyright
on Python versions 2.1 and newer. The PSF’s mission is to advance open source technology related
to the Python programming language and to publicize the use of Python. The PSF’s home page is
athttps://www.python.org/psf/. You can do anything you want with the source.
The name "Python" was adopted from the same series "Monty Python's Flying Circus".
2.2. PYTHON INSTALLATION:
Downloading steps:
1. Go to: https://www.python.org/downloads/
The file named python-3.6.2.exe should start downloading into your standard download
folder. This file is about 30 Mb so it might take a while to download fully if you are on a
slow internet connection (it took me about 10 seconds over a cable modem). The file
appears as an exe file.
3. Move this file to a more permanent location, so that you can install Python (and reinstall it
easily later, if necessary).
Ensure that the Install launcher for all users (recommended) and the Add Python 3.6 to
PATH checkboxes at the bottom are checked.
If the Python Installer finds an earlier version of Python installed on your computer, the Install
Now message will instead appear as Upgrade Now (and the checkboxes will not appear).
5. Highlight the Install Now (or Upgrade Now) message, and then click it.
A User Account Conrol pop-up window will appear, posing the question
Do you want to allow the following program to make changes to this computer?
6. Click the Yes button.
A new Python 3.6.2 (32-bit) Setup pop-up window will appear with a Setup Progress message
and a progress bar.
During installation, it will show the various components it is installing and move the progress bar
towards completion. Soon, a new Python 3.6.2 (32-bit) Setup pop-up window will appear with
a Setup was successfuly message.
7. Click the Close button.
Let's write our first Python program, "Hello, World!". It's a simple program that prints Hello
World!
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World");
Hello, World
>>>
Example programs:
1. Program to Add Two Numbers
Line1: # Add two numbers
Line2: num1 = 10
Line3: num2 = 20
Line5: print(sum)
The above program works like this:
Comments are used in programming to describe the purpose of the code. This helps you as well as
other programmers to understand the intent of the code. Comments are completely ignored by
compilers and interpreters.
Line 2: num1 = 10
Here, num1 is a variable. You can store a value in a variable. Here, 10 is stored in this variable.
Line 3: num2 = 20
The variables num1 and num2 are added using + operator. The result of addition is then stored in
another variable sum.
Line 5: print(sum)
The print() function prints the output to the screen. In our case, it prints 30 on the screen.
Python Keywords:
There are 33 keywords in Python 3.3. All the keywords except True, False and None are in
lowercase and they must be written as it is.
False class finally is return
as elif if or yield
Types of Operator :
Python language supports the following types of operators.
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Following is the general form of a typical decision making structure found in most of the
programming languages −
Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements. Click the
following links to check their detail.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
If the suite of an if clause consists only of a single line, it may go on the same line as the header
statement.
Here is an example of a one-line if clause.
var = 100
Loop: A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement:
Python programming language provides following types of loops to handle looping requirements.
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Flow Diagram
Python supports the following control statements. Click the following links to check their detail.
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
1.break statement
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.
Syntax
The syntax for a break statement in Python is as follows −
Break
Flow Diagram
2. continue statement
It returns the control to the beginning of the while loop.. The continue statement rejects all the
remaining statements in the current iteration of the loop and moves the control back to the top of
the loop.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
Week 3
Platform Based Development – Raspberry Pi
2. Double-click on the NOOBS file from the Downloads folder in your Dock to open it
Insert the microSD card into the card slot on the underside of the Raspberry Pi.
Alternatively, connect the Bluetooth adapter into one of the USB ports.
Turn on your monitor or TV set and make sure it is set to the proper input (e.g. HDMI 1 or
Component)
Plug the HDMI or video component cable into the monitor or TV set.
Connect the other end of the cable into the Raspberry Pi.
Connect an ethernet cable to your router if you plan to connect to the Internet.
Connect the other end of the cable to your Raspberry Pi.
Plug the power supply into the power outlet. This will turn on and boot up Raspberry Pi. A
power indicator light will begin to glow, letting you know that you are connected,
3.4. Platform Based Development-Raspberry Pi
Week 4
Experiment 1
Components Required:
Connecting pins
1KΩresistor
LED
Bread Board
Circuit Explanation:
As shown in the circuit diagram we are going to connect an LED between PIN8 and PIN39
(GROUND) so to limit the current we are connecting a 1KΩ resistor in series with the LED.
Working Explanation:
2. After that, PYHON will run and you will see a window as shown in below figure.
3. After that, click on New File in File Menu, You will see a new Window open
4. Save this file as blinkpy on the desktop
5. After that write the program for blinkpy as given below and execute the program by clicking on
“RUN” on ‘DEBUG’ option.
If the program has no errors in it, you will see a “>>>”, which means the program is executed
successfully. By this time you should see the LED blinking three times. If there were any errors in
the program, the execution tells to correct it. Once the error is corrected execute the program again.
Code Explanation:
In the Python program, first we have imported two packages RPi.GPIO and Time. The
package RPi.GPIO will help us in controlling the GPIO Pins of the Raspberry Pi.
The first important function of the RPi.GPIO Module is the setmode(). Using GPIO.setmode(), we
can select either GPIO Numbering of the Pins or Physical Numbering. By
using GPIO.setmode(GPIO.BOARD), we are selecting the Physical Numbering Scheme.
The next function is the setup(pin,mode). This function will allow us to set the pin as either input
(GPIO.IN) or as output (GPIO.OUT). In the program, I have set the ledPin as output by
using GPIO.setup(ledPin, GPIO.OUT).After setting the LED Pin as OUTPUT, now we need to
set the state of this OUTPUT i.e. HIGH (GPIO.HIGH) or LOW (GPIO.LOW). For this, we need to
use the function output(pin, state). So, in our program, we need to use GPIO.output(ledPin,
GPIO.HIGH) for turning ON the LED and GPIO.output(ledPin, GPIO.LOW) for turning it
OFF.
Code:
GPIO.output(8,False)
print("LED IS OFF")
time.sleep(3)
Output:
LED IS ON
LED IS OFF
Experiment 2
Components Required:
1. Raspberry Pi 3
2. Breadboard
4. 3 resistors
5. Jumper wires
The LED is the abbreviation of light emitting diode. The LED has two electrodes, a positive
electrode and a negative electrode. It lights up only when a forward current passes. The RGB LEDs
consist of three LEDs in different colors:red, green and blue. These three colored LEDs are capable
of producing any color. Tri-color LEDs with red, green, and blue emitters, in general use a four-
wire connection with one common lead (anode or cathode).
The symbol for common anode RGB LED
Circuit Explanation:
The longest pin is the common anode of the three LEDs. The pin is connected to the +3.3V pin of
the Raspberry Pi, and the rest pins are connected to pin 8, pin 10, and pin 12 of Raspberry Pi with a
current limiting resistor between(220Ω). Using these pins, we can control the color of the RGB
LED by 3-channel PWM signal.
Code Explanation:
GPIO.output(8,False)
print("RED OFF")
time.sleep(3)
GPIO.output(10,True)
print("GREEN ON")
time.sleep(3)
GPIO.output(10,False)
print("GREEN OFF")
time.sleep(3)
GPIO.output(12,True)
print("BLUE ON")
time.sleep(3)
GPIO.output(12,False)
print("BLUE OFF")
time.sleep(3)
OUTPUT:
RED ON
RED OFF
GREEN ON
GREEN OFF
BLUE ON
BLUE OFF
Week5
Experiment-3
Components Required:
IR Sensor Module:
IR sensors (Infrared sensor) are modules which detect the presence of objects before them. If the
object is present it give 3.3V as output and if it is not present it gives 0 volt. This is made possible
by using a pair of IR pair (transmitter and receiver), the transmitter (IR LED) will emit an IR ray
which will get reflected if there is a object present before it. This IR ray will be received back by
the receiver.
The circuit diagram for connecting Raspberry Pi with IR sensor is shown below. As you can see the
circuit diagram is very simple. We have directly powered the IR module from the 5V and Ground
Pin of Raspberry Pi. The output pin of the IR module is connected to the GPIO14. We have also
used two LED (Green and Red) to indicate the status of the object. These two LEDs are connected
to GPIO3 and GPIO2 respectively.
Working:
Once you have created your python code, execute it using the run command. If the program is
executed without any errors you should get the following screen.
Code:
Output:
AIM: Counting the number Persons entering the room using IR Sensor
Components Required:
Code:
Output:
First person is entered
Second person is entered
.
.
.
Experiment-5
Components Required:
Push Button
Bread Board
Led
Raspberry pi model 3
Jumper Wires(M-F)
Resistor
Working Explanation:
A Push Button is a type of switch work on a simple mechanism called “Push-to-make”. Initially,
it remains in off state or normally open state but when it is pressed, it allows the current to pass
through it or we can say it makes the circuit when pressed.
CODE:
import time
GPIO.setmode(GPIO.BOARD)
Led=8
Button=10
GPIO.setup(led,GPIO.OUT)
while True:
bs=GPIO.input(button)
print("led off")
while bs==1:
GPIO.output(led, GPIO.LOW)
bs=GPIO.input(button)
print("led on")
while bs==0:
GPIO.output(led, GPIO.HIGH)
bs=GPIO.input(button)
OUTPUT:
LED OFF
LED ON
Week 6
Experiment 6
Aim: To interface the Ultrasonic Sensor with the Raspberry Pi3 to determine the distance of an
object from the sensor
Components Required:
HC-SR04
1kΩ Resistor
2kΩ Resistor
Jumper Wires
Circuit Explanation:
There are four pins on the ultrasound module that are connected to the Raspberry:
VCC to Pin 2 (VCC)
GND to Pin 6 (GND)
TRIG to Pin 8
ECHO to Pin 10
An ultrasonic distance sensor sends out pulses of ultrasound which are inaudible to humans,
and detects the echo that is sent back when the sound bounces off a nearby object. It then uses
the speed of sound to calculate the distance from the object.
Code:
#Libraries
import RPi.GPIO as GPIO
import time
def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
StartTime = time.time()
StopTime = time.time()
# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
time.sleep(1)
OUTPUT:
Experiment 7
AIM: To control an LED according to the range of analog input sensed using photo resistor. (use
Light Dependant Resistor(LDR ))
Components Required:
LDR
1kΩ Resistor
Jumper Wires
Working Explanation:
The light dependent resistor or also known as the LDR sensor is the most important piece of
equipment in our circuit (obviously). Without it, we wouldn’t be able to detect whether it is dark or
light.
In the light, this sensor will have a resistance of only a few hundred ohms while in the dark, it can
have a resistance of several megohms.
To get the light sensor circuit built correctly follow the steps below or check out the circuit diagram
right underneath the steps. In the following steps, I am referring to the physical numbers of the pins
(Logical order).
1. First, connect pin #1 (3v3) to the positive rail on the breadboard.
3. Now place the LDR sensor onto the board and have a wire go from one end to the positive rail.
4. On the other side of the LDR sensor place a wire leading back to the Raspberry Pi. Hook this to
pin #7.
CODE:
import time
from gpioZero import LightSensor
ldr= LightSensor(4)
while True:
print(ldr.value)
time.sleep(1)
OUTPUT:
9.8372354212
9.7372353471
ANDROID
WEEK 7
The Android SDK includes a complete set of development tools. It includes a debugger,
libraries, a handset emulator.
Software written in Java can be compiled to be executed in the Dalvik virtual machine,
which is a specialized VM implementation designed for mobile device use.
Required Software to Install Android ?
1. JDK6 Version
2. Android SDK for Windows (if you have Windows OS)
3. Eclipse IDE
Step 1. Once we download the exe file we can now install it. Just follow what
mentioned below: To install the jdk, double click on the downloaded exe file (jdk-6u1-
windows-i586-p.exe) Double Click the icon of downloaded exe from the downloaded
location.
Click the "Change" button to choose the installation directory of Runtime Environment. We prefer
not to change it. So click "OK" button.
Step 6: Click "OK" button starts the installation.
Step 7: Now "Complete" window appears indicating that installation of jdk 1.6 has completed
successfully. Click "Finish" button to exit from the installation process.
Step 8: The above installation will create two folders "jdk1.6.0_01" and
Ensure the following installed Android SDK location in file system, and click on SDK
manager from the android-sdk directory.
Step-5) This step is very important , from the following Window, select tools, API Levels
like API15, API 10, ..etc , and also select Extras-> Google USB Driver package for USB
Connections with real device.
Click on Install XX Packages button.
Click OK.
If you have trouble for the plugin, try using "http" in the Location URL, instead of "https" (https is
preferred for security reasons).
In the Available Software dialog, select the checkbox next to Developer Tools and click
Next.
In the next window, we'll see a list of the tools to be downloaded. Click Next.
After we've installed ADT and restarted Eclipse, we must specify the location of our
Android SDK directory:
3. For the SDK Location in the main panel, click Browse... and locate your downloaded
Android SDK directory (such as android-sdk-windows).
4. Click Apply, thenOK.
Note :“With this your Android Installation part is completed, we can configure Android
plugin for other IDE’s like Netbeans, IntelliJ IDE also. “
AVD, stands Android Virtual Device, AVD’s are used to start emulator. When we
launch the emulator, we should specify the AVD configuration that we want to
load..
Before Configuring AVD, first confirm SDK tools and API levels are installed or not !
Then select AVD Manager from Window -> AVD Manager.
Click New... button, name your new AVD, select API target, SD Card size, then click
Create AVD button.
Click Start... button to start your new AVD. It will takes a few minutes for
creating new AVD.
What is Emulator ? How to Start ?
The emulator lets you prototype, develop and test Android applications without using a
physical device.
To use the emulator, first we must create AVD configuration, Remember, If project
is used with Android API15 level , then we should use AVD API level also 15.
Every Emulator needs one AVD support, because the AVD configuration provides both software
and hardware support for Emulator, like it can use the services of the Android platform to invoke
other applications, access the network, play audio and video, store and retrieve data, notify the user,
and render graphical transitions and themes.
Select from the menu File --> New --> Other --> Android --> Android Application Project (say
'AndroidHello') and click Nextbutton.
Enter Application, Project and Package Name. Select 'Minimum Required SDK' (lowest
version of Android that this app supports), 'Target SDK' (highest version of Android with which
this application has been tested), 'Compile With' (platform version against which this
application will be compiled with) and 'Theme' (Android UI style) from the corresponding
theme. To make it simple you can leave the dropdown value as it is. Click Next button
Click Next button
4. Create Activity
Choose an activity template (say 'Blank Activity') and click Next button.
Enter 'Activity Name' (say 'Hello Activity') and click Finish button.
Android project will be created with some default files as shown below
6. Code
activity_hello.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
File : HelloActivity.java
package com.srccodes.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
tv=( TextView)findviewbyId(id.textview1);
tv.settext(“HelloWorld”);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_hello, menu);
return true;
}
}
OUTPUT:
Week 8
Code
activity_hello.xml
<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:Background="#0000FF"
tools:context=".HelloActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
File : HelloActivity.java
package com.srccodes.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
tv=( TextView)findviewbyId(id.textview1);
tv.settext(“HelloWorld”);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_hello, menu);
return true;
}
}
OUTPUT:
Week 9
Create an application that display color or image as background when selected the radio
buttons or checkboxes
Create an Application to perform addition, Subtraction, multiplication, division.
Code
activity_hello.xml
</RelativeLayout>
File : HelloActivity.java
package com.srccodes.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class HelloActivity extends Activity {
TextView tv;
RadioButton rb;
CheckBox cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
tv=( TextView)findviewbyId(id.textview1);
tv.settext(“HelloWorld”);
rb=( radiobutton)findviewbyId(id. radiobutton1);
cb=( checkbox)findviewbyId(id. checkbox1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_hello, menu);
return true;
}
}
OUTPUT:
Week 10
i) Create an application with Android intent.
Code
activity_Button.xml
</RelativeLayout>
package com.example.intent12;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
Button bt;
@Override
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
@Override
startActivity(in);
});
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu)
return true;
}}
OUTPUT:
Week 11
Create a simple android application with the following event handlers.
On Click
Code
Hello activity_.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
File :HelloActivity.java
package com.example.onclick12;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.button1);
Toast.makeText(getApplicationContext(), "tulsi", 1000).show();
tv=(TextView)findViewById(R.id.textView1);
tv.setText("ur pressed 1");
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
OUTPUT:
package com.example.onkeydown;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloActivity" >
<Edittext
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Edittext
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed=(EditText)findViewById(R.id.editText1);
ed1=(EditText)findViewById(R.id.editText2);
ed.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if(arg1)
Toast.makeText(getApplicationContext(), "ed has focus",
2000).show();
else
Toast.makeText(getApplicationContext(), "ed1 has not focus",
1000).show();
}
});
//ed1=(EditText)findViewById(R.id.editText2);
ed1.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if(arg1)
Toast.makeText(getApplicationContext(), "edit text1 has focus", 2000).show();
else
Toast.makeText(getApplicationContext(), "edit text has not focus", 1000).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.activity_main, menu);
return true;
}
OUTPUT:
Week 12
Explain about Toast, Create Application with User defined Toast Notifications.
Create login page by using login activity.
Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.
You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Method Description
public static Toast makeText(Context context, makes the toast containing text and
CharSequence text, int duration) duration.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.
Code
activity_ Toast .xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello" />
<Button
android:id="@+id/ Button1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text=" Toast "
android:textsize=”25sp”/>
</RelativeLayout>
package com.example.toast3;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
Button bt;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
@Override
}) ;
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
OUTPUT: