Computer Lab-X Lab Manual BEIT (2015 Course)
Computer Lab-X Lab Manual BEIT (2015 Course)
Information Technology
LABORATORY MANUAL
b. An ability to define a problem and provide a systematic solution with the help of conducting
experiments, as well as analyzing and interpreting the data.
e. An ability to use the techniques, skills, and modern engineering technologies tools, standard
processes necessary for practice as an IT professional.
g. An ability to analyze the local and global impact of computing on individuals, organizations
and society.
h. An ability to understand professional, ethical, legal, security and social issues and
responsibilities.
m. An ability to apply design and development principles in the construction of software systems
Compliance
Document Control
Authors
Syllabus
Prerequisites:
Course Objectives:
2. To design applications for accessing smart devices and data generated through
sensors and services.
Course Outcomes:
1. Set up the Android environment and explain the Evolution of cellular networks.
3. Create applications for performing CURD SQLite database operations using Android.
4. Create the smart android applications using the data captured through sensors.
5. Implement the authentication protocols between two mobile devices for providing. Security.
6. Analyze the data collected through android sensors using any machine learning algorithm.
Tools Required Android SDK / Android Studio, SQL Lite, Sensors, Arduino kit.
Laboratory Assignments
1. Android development environment. Installing and setting up the environment. Hello world
application. Running the emulator. Inserting debug messages.
2. Android UI Design: Design a User Interface using pre-built UI components such as structured
layout objects, UI controls and special interfaces such as dialogs, notifications, and menus.
Also make this UI attractive using Android graphics platform OpenGL.
4. Develop a Smart Light System (Light that automatically switched on in evening and gets off
in morning) using open source Hardware platform like Arduino and some sensors (Light
dependent resistor) and actuator (An LED)
5. Design and Develop a GUI for FAN regulator that uses Android platform.
6. Develop an Android based FAN regulator using open source Hardware platform like
NodeMcu and actuator (a SERVO Motor).
7. Wireless Network: Develop an app for a rolling display program of news on computer display.
The input strings are supplied by the mobile phone/ by another computer connected through
wireless networks.
1. https://developer.android.com/
2. https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
3. https://developers.google.com/android/guides/api-client
4. https://developer.android.com/guide/topics/sensors/sensors_overview
Title No. of
Sr. Week
Hrs.
No.
Android development environment. Installing and setting
1 2 1
up the environment. Hello world application. Running the
emulator. Inserting debug messages.
Objective:
Theory:
Android Studio is Google's IDE for Android apps. Android Studio gives you an advanced code
editor and a set of app templates. In addition, it contains tools for development, debugging,
testing, and performance that make it faster and easier to develop apps. You can test your apps
with a large range of preconfigured emulators or on your own mobile device, and build production
APKs for publication.
You may need to install the Java Development Kit - Java 7 or better.
Install Android Studio
Android Studio is available for Windows, Mac, and Linux computers. The installation is similar
for all platforms. Any differences will be noted in the sections below.
1. Navigate to the Android developers site and follow the instructions to download and install
Android Studio.
2. After finishing the install, the Setup Wizard will download and install some additional
components.
3. When the download completes, Android Studio will start, and you are ready to create your first
project.
In this task, you will implement the "Hello World" app to verify that Android studio is correctly
installed and learn the basics of developing with Android Studio.
o Apps published to the Google Play Store must have a unique package name. Since
domains are unique, prepending your app's name with your or your company's
domain name is going to result in a unique package name.
o If you are not planning to publish your app, you can accept the default example
domain. Be aware that changing the package name of your app later is extra
work.
6. Verify that the default Project location is where you want to store your Hello World app and
other Android Studio projects, or change it to your preferred directory. Click Next.
7. On the Target Android Devices screen, "Phone and Tablet" should be selected.
8. Click Next.
The Android Studio window should look similar to the following diagram:
1. Click on the Hello World folder to expand the hierarchy of files (1),
2. Click on Project (2).
3. Click on the Android menu (3).
4. Explore the different view options for your project.
In this practical, you will explore how the project files are organized in Android Studio.
These steps assume that your Hello World project starts out as shown in the diagram above.
In the Project > Android view of your previous task, there are three top-level folders below your
appfolder: manifests, java, and res.
This folder contains AndroidManifest.xml. This file describes all of the components of your
Android app and is read by the Android run-time system when your program is executed.
2. Expand the java folder. All your Java language files are organized in this folder.
The java folder contains three subfolders:
o com.example.hello.helloworld (or the domain name you have specified): All the files for a
package are in a folder named after the package. For your Hello World application, there is one
package and it only contains MainActivity.java (the file extension may be omitted in the Project
view).
o com.example.hello.helloworld(androidTest): This folder is for your instrumented tests, and
starts out with a skeleton test file.
o com.example.hello.helloworld(test): This folder is for your unit tests and starts out with an
automatically created skeleton unit test file.
3. Expand the res folder. This folder contains all the resources for your app, including images,
layout files, strings, icons, and styling. It includes these subfolders:
o drawable. Store all your app's images in this folder.
o layout. Every activity has at least one layout file that describes the UI in XML. For Hello World,
this folder contains activity_main.xml.
o mipmap. Store your launcher icons in this folder. There is a sub-folder for each supported screen
density. Android uses the screen density, that is, the number of pixels per inch to determine the
required image resolution. Android groups all actual screen densities into generalized densities,
such as medium (mdpi), high (hdpi), or extra-extra-extra-high (xxxhdpi). The ic_launcher.png
folder contains the default launcher icons for all the densities supported by your app.
o values. Instead of hardcoding values like strings, dimensions, and colors in your XML and Java
files, it is best practice to define them in their respective values file. This makes it easier to
change and be consistent across your app.
4. Expand the values subfolder within the res folder. It includes these subfolders:
o colors.xml. Shows the default colors for your chosen theme, and you can add your own colors or
change them based on your app's requirements.
o dimens.xml. Store the sizes of views and objects for different resolutions.
o strings.xml. Create resources for all your strings. This makes it easy to translate them to other
languages.
o styles.xml. All the styles for your app and theme go here. Styles help give your app a consistent
look for all UI elements.
Android Studio uses Gradle as its build system. As you progress through these practicals, you
will learn more about gradle and what you need to build and run your apps.
1. Expand the Gradle Scripts folder. This folder contains all the files needed by the build system.
2. Look for the build.gradle(Module:app) file. When you are adding app-specific dependencies,
such as using additional libraries, they go into this file.
In this task, you will use the Android Virtual Device (AVD) manager to create a virtual device
or emulator that simulates the configuration for a particular type of Android device.
Using the AVD Manager, you define the hardware characteristics of a device and its API level,
and save it as a virtual device configuration.
When you start the Android emulator, it reads a specified configuration and creates an emulated
device that behaves exactly like a physical version of that device , but it resides on your computer
.
Why: With virtual devices, you can test your apps on different devices (tablets, phones) with
different API levels to make sure it looks good and works for most users. You do not need to
depend on having a physical device available for app development.
In order to run an emulator on your computer, you have to create a configuration that describes
the virtual device.
1. In Android Studio, select Tools > Android > AVD Manager, or click the AVD Manager
The Select Hardware screen appears showing a list of preconfigured hardware devices. For each
device, the table shows its diagonal display size (Size), screen resolution in pixels (Resolution),
and pixel density (Density).
For the Nexus 5 device, the pixel density is xxhdpi, which means your app uses the launcher icons
in the xxhdpi folder of the mipmap folder. Likewise, your app will use layouts and drawables
from folders defined for that density as well.
There are many more versions available than shown in the recommended tab. Look at
the x86 Images and Other Images tabs to see them.
5. If a Download link is visible next to a system image version, it is not installed yet, and you need
to download it. If necessary, click the link to start the download, and click Finish when it's done.
6. On System Image screen, choose a system image and click next.
7. Verify your configuration, and click Finish. (If the Your Android Devices AVD Manager
window stays open, you can go ahead and close it.)
In this task, you will finally run your Hello World app.
1. In Android Studio, select Run > Run app or click the Run icon in the toolbar.
2. In the Select Deployment Target window, under Available Emulators, select Nexus 5
API 23 and click OK.
The emulator starts and boots just like a physical device. Depending on the speed of your
computer, this may take a while. Your app builds, and once the emulator is ready, Android Studio
will upload the app to the emulator and run it.
You should see the Hello World app as shown in the following screenshot.
In this practical, you will add log statements to your app, which are displayed in the logging
window of the Android Monitor.
Why: Log messages are a powerful debugging tool that you can use to check on values,
execution paths, and report exceptions.
1. Click the Android Monitor button at the bottom of Android Studio to open the Android
Monitor.
By default, this opens to the logcat tab, which displays information about your app as it is
running. If you add log statements to your app, they are printed here as well.
You can also monitor the Memory, CPU, GPU, and Network performance of your app from the
other tabs of the Android Monitor. This can be helpful for debugging and performance tuning
your code.
2. The default log level is Verbose. In the drop-down menu, change the log level to Debug.
1. Open your Hello World app in Android studio, and open MainActivity file.
Solution Code:
package com.example.hello.helloworld;
import android.os.Bundle;
import
android.support.v7.app.AppCompatActivity;
import android.util.Log;
Every app includes an Android Manifest file (AndroidManifest.xml).The manifest file contains
essential information about your app and presents this information to the Android runtime system.
Android must have this information before it can run any of your app's code.
In this practical you will find and read the AndroidManifest.xml file for the Hello World app.
1. Open your Hello World app in Android studio, and in the manifests folder,
openAndroidManifest.xml.
2. Read the file and consider what each line of code indicates. The code below is annotated to
give you some hints.
Computer Lab-X (BEIT 2015 Course) Page 20 of
108
Annotated code:
Android Studio uses a build system called Gradle. Gradle does incremental builds, which allows
for shorter edit-test cycles.
1. In your project hierarchy, find Gradle Scripts and expand it. There several build.gradle files.
One with directives for your whole project, and one for each app module. The module for your
app is called "app". In the Project view, it is represented by the app folder at the top- level of the
Project view.
2. Open build.gradle (Module.app).
3. Read the file and learn what each line of code indicates.
Solution:
In this final task, you will run your app on a physical mobile device such as a phone or tablet.
Why: Your users will run your app on physical devices. You should always test your apps on
both virtual and physical devices.
To let Android Studio, communicate with your device, you must turn on USB Debugging on your
Android device. This is enabled in the Developer options settings of your device. Note this is not
the same as rooting your device.
On Android 4.2 and higher, the Developer options screen is hidden by default. To show Developer
options and enable USB Debugging:
Now you can connect your device and run the app from Android Studio.
Android Studio should install and runs the app on your device.
Conclusion:
Thus we know how to Install and use the Android IDE. Also we understand the development
process for building Android apps. We have created an Android project from a basic app
template.
FAQs:-
Instant?
app?
Objective:
Theory:
Your app's user interface is everything that the user can see and interact with. Android
provides a variety of pre-built UI components such as structured layout objects and UI
controls that allow you to build the graphical user interface for your app. Android also
provides other UI modules for special interfaces such as dialogs, notifications, and menus.
Layouts
A layout defines the structure for a user interface in your app, such as in an activity. All elements
in the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas a ViewGroup is an invisible container that
defines the layout structure for View and other ViewGroup objects, as shown in figure 1.
The View objects are usually called "widgets" and can be one of many subclasses, such as
Button or TextView. The ViewGroup objects are usually called "layouts" can be one of many
types that provide a different layout structure, such as LinearLayout or ConstraintLayout .
When you compile your app, each XML layout file is compiled into a View resource. You should
load the layout resource from your app code, in your Activity.onCreate() callback
implementation. Do so by calling setContentView(), passing it the reference to your layout
resource in the form of: R.layout.layout_file_name. For example, if your XML layout is saved
as main_layout.xml, you would load it for your Activity like so:
JAVA
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
The onCreate() callback method in your Activity is called by the Android framework when your
Activity is launched (see the discussion about lifecycles, in the Activities document).
Attributes
Every View and ViewGroup object supports their own variety of XML attributes. Some attributes
are specific to a View object (for example, TextView supports the textSize attribute), but these
attributes are also inherited by any View objects that may extend this class. Some are common to
all View objects, because they are inherited from the root View class (like the idattribute). And,
other attributes are considered "layout parameters," which are attributes that describe certain
layout orientations of the View object, as defined by that object's parent ViewGroup object.
ID
Any View object may have an integer ID associated with it, to uniquely identify the View within
the tree. When the app is compiled, this ID is referenced as an integer, but the ID is typically
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and
expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that
this is a new resource name that must be created and added to our resources (in the R.javafile).
There are a number of other ID resources that are offered by the Android framework. When
referencing an Android resource ID, you do not need the plus-symbol, but must add the
android package namespace, like so:
android:id="@android:id/empty"
With the android package namespace in place, we're now referencing an ID from
the android.R resources class, rather than the local resources class.
In order to create views and reference them from the app, a common pattern is to:
<Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/
>
2. Then create an instance of the view object and capture it from the layout (typically in the
onCreate() method):
JAVA
Button myButton = (Button) findViewById(R.id.my_button);
Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout,
sibling views can define their layout relative to another sibling view, which is referenced by the
unique ID.
An ID need not be unique throughout the entire tree, but it should be unique within the part of the
tree you are searching (which may often be the entire tree, so it's best to be completely unique
when possible).
XML layout attributes named layout_something define layout parameters for the View that are
appropriate for the ViewGroup in which it resides.
Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This
subclass contains property types that define the size and position for each child view, as
appropriate for the view group. As you can see in figure 2, the parent view group defines layout
parameters for each child view (including the child view group).
Figure 2. Visualization of a view hierarchy with layout parameters associated with each view
Note that every LayoutParams subclass has its own syntax for setting values. Each child element
must define LayoutParams that are appropriate for its parent, though it may also define different
LayoutParams for its own children.
All view groups include a width and height (layout_width and layout_height), and each view is
required to define them. Many LayoutParams also include optional margins and borders.
You can specify width and height with exact measurements, though you probably won't want to do
this often. More often, you will use one of these constants to set the width or height:
wrap_content tells your view to size itself to the dimensions required by its content.
match_parent tells your view to become as big as its parent view group will allow.
In general, specifying a layout width and height using absolute units such as pixels is not
recommended. Instead, using relative measurements such as density-independent pixel units (dp),
wrap_content, or match_parent, is a better approach, because it helps ensure that your app will
display properly across a variety of device screen sizes. The accepted measurement types are
defined in the Available Resources document.
Computer Lab-X (BEIT 2015 Course) Page 30 of
108
Layout Position
The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of
leftand top coordinates, and two dimensions, expressed as a width and a height. The unit for
location and dimensions is the pixel.
It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop().
The former returns the left, or X, coordinate of the rectangle representing the view. The latter
returns the top, or Y, coordinate of the rectangle representing the view. These methods both return
the location of the view relative to its parent. For instance, when getLeft() returns 20, that means
the view is located 20 pixels to the right of the left edge of its direct parent.
In addition, several convenience methods are offered to avoid unnecessary computations, namely
getRight() and getBottom(). These methods return the coordinates of the right and bottom edges
of the rectangle representing the view. For instance, calling getRight() is similar to the following
computation: getLeft() + getWidth().
The size of a view is expressed with a width and a height. A view actually possesses two pairs of
width and height values.
The first pair is known as measured width and measured height. These dimensions define how
big a view wants to be within its parent. The measured dimensions can be obtained by calling
getMeasuredWidth() and getMeasuredHeight().
The second pair is simply known as width and height, or sometimes drawing width and drawing
height. These dimensions define the actual size of the view on screen, at drawing time and after
layout. These values may, but do not have to, be different from the measured width and height.
The width and height can be obtained by calling getWidth() and getHeight().
To measure its dimensions, a view takes into account its padding. The padding is expressed in
pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content
of the view by a specific number of pixels. For instance, a left padding of 2 will push the view's
content by 2 pixels to the right of the left edge. Padding can be set using
the setPadding(int, int, int, int) method and queried by
callin getPaddingLeft getPaddingTop and getPaddingBottom().
g (), (),
getPaddingRigh
t()
Even though a view can define a padding, it does not provide any support for margins.
However, view groups provide such a support. Refer
to ViewGroup andViewGroup.MarginLayoutParams for further information.
Computer Lab-X (BEIT 2015 Course) Page 31 of
108
For more information about dimensions, see Dimension Values.
Common Layouts
Each subclass of the ViewGroup class provides a unique way to display the views you nest within
it. Below are some of the more common layout types that are built into the Android platform.
Note: Although you can nest one or more layouts within another layout to achieve your
UI design, you should strive to keep your layout hierarchy as shallow as possible. Your
layout draws faster if it has fewer nested layouts (a wide view hierarchy is better than a
deep view hierarchy).
Linear Layout
A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar
if the length of the window exceeds the length of the screen.
Relative Layout
Enables you to specify the location of child objects relative to each other (child A to the left of
child B) or to the parent (aligned to the top of the parent).
You can use built in vies to Design your activity as per requirement. You just drag and drop the
views and set their attributes.
Refer img to design and activity.
Dialogs
A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events that require
users to take an action before they can proceed.
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.
Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To
perform event handling on menu items, you need to override onOptionsItemSelected() method of
Activity class.
There are 3 types of menus in Android:
2. Context Menu: 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.
3. Pop-up Menu : A popup menu displays a list of items in a vertical list that is
anchored(sticked) 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.
How to create a Menu?
For all menu types mentioned above, 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 i.e load the XML files
as a Menu object in your activity.
<menu>
It 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>
<group>
It is an optional, invisible container for <item> elements. It allows you to categorize menu
items so they share properties such as active state and visibility.
menu_file.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/i1"
android:title="item"
>
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
<TextView
android:id="@+id/textView
"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="51dp"
android:textSize="35sp"
android:text="This is new activity"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
<TextView
android:id="@+id/t1
"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am context menu"
android:paddingBottom="30dp"
android:textAllCaps="true"
android:textSize="20sp"
android:layout_marginTop="11dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
/>
<Button
android:id="@+id/button
"
android:layout_width="wrap_content
"
Computer Lab-X (BEIT 2015 Course) Page 42 of
108
android:layout_height="wrap_conten
t" android:onClick="pop"
android:text="I am Pop Menu"
Main2Activity.java
package comjdjaydeeppatil.trialscoe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
registerForContextMenu((TextView)findViewById(R.id.t1));
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_file,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Computer Lab-X (BEIT 2015 Course) Page 44 of
108
switch (item.getItemId()){
case R.id.i1:
Toast.makeText(this,"Cicked Main
Menu",Toast.LENGTH_SHORT).show(); break;
case R.id.i2:
Toast.makeText(this,"I am sub-menu
1",Toast.LENGTH_SHORT).show(); break;
case R.id.i3:
Toast.makeText(this,"I am sub-menu
2",Toast.LENGTH_SHORT).show(); break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View
v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_file,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.i1:
Toast.makeText(this,"Clicked Main
menu",Toast.LENGTH_SHORT).show(); break;
case R.id.i2:
Toast.makeText(this,"I am sub-menu
1",Toast.LENGTH_SHORT).show(); break;
case R.id.i3:
Toast.makeText(this,"I am sub-menu
2",Toast.LENGTH_SHORT).show(); break;
}
return true;
{
switch (item.getItemId()){
case R.id.i1:
Toast.makeText(this,"Clicked Main
menu",Toast.LENGTH_SHORT).show(); break;
case R.id.i2:
Toast.makeText(this,"I am sub-menu
1",Toast.LENGTH_SHORT).show(); break;
case R.id.i3:
Toast.makeText(this,"I am sub-menu
2",Toast.LENGTH_SHORT).show(); break;
}
return true;
}
}
Aim: Android-database Connectivity: Create a SQLite Database for an Android Application and
perform CRUD (Create, Read, Update and Delete) database operations.
Theory:
What is SQLite?
SQLite is an SQL Database. So in SQL database, we store data in tables. The tables are the
structure of storing data consisting of rows and columns.
What is CRUD?
As the heading tells you here, we are going to learn the CRUD operation in SQLite Database. But
what is CRUD? CRUD is nothing but an abbreviation for the basic operations that we perform
in any database. And the operations are
Create
Read
Update
Delete
Android SQLite
Android SQLite is a very lightweight database which comes with Android OS. Android SQLite
combines a clean SQL interface with a very small memory footprint and decent speed. For
Android, SQLite is “baked into” the Android runtime, so every Android application can create its
own SQLite databases.
Android SQLite native API is not JDBC, as JDBC might be too much overhead for a memory-
limited smartphone. Once a database is created successfully its located in
data/data//databases/ accessible from Android Device Monitor.
SQLite is a typical relational database, containing tables (which consists of rows and columns),
indexes etc. We can create our own tables to hold the data accordingly. This structure is referred to
as a schema.
Android has features available to handle changing database schemas, which mostly depend on
using the SQLiteOpenHelper class.
1. When the application runs the first time – At this point, we do not yet have a database. So
we will have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema – Our database will still be on the old
schema from the older edition of the app. We will have option to alter the database schema
to match the needs of the rest of the app.
SQLiteOpenHelper wraps up these logic to create and upgrade a database as per our
specifications. For that we’ll need to create a custom subclass
of SQLiteOpenHelper implementing at least the following three methods.
1. Constructor: This takes the Context (e.g., an Activity), the name of the database, an
optional cursor factory (we’ll discuss this later), and an integer representing the version
of the database schema you are using (typically starting from 1 and increment later).
DB_VERSION);
1. onCreate(SQLiteDatabase db) : It’s called when there is no database and the app needs
one. It passes us a SQLiteDatabase object, pointing to a newly-created database, that we
can populate with tables and initial data.
2. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s called when the
schema version we need does not match the schema version of the database, It passes us a
SQLiteDatabase object and the old and new version numbers. Hence we can figure out the
best way to convert the database from the old schema to the new one.
We define a DBManager class to perform all database CRUD(Create, Read, Update and Delete)
operations.
Before performing any database operations like insert, update, delete records in a table, first open
the database connection by calling getWritableDatabase() method as shown below:
database = dbHelper.getWritableDatabase();
return this;
method is invoked.
dbHelper.close();
The following code snippet shows how to insert a new record in the android SQLite database.
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
Content Values creates an empty set of values using the given initial size. We’ll discuss the other
instance values when we jump into the coding part.
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
null); return
i;
A Cursor represents the entire result set of the query. Once the query is fetched a call
to cursor.moveToFirst()is made. Calling moveToFirst() does two things:
It allows us to test whether the query returned an empty set (by testing the return value)
It moves the cursor to the first result (when the set is not empty)
if (cursor != null) {
cursor.moveToFirst()
return cursor;
Implementation:
Step 2 – Add components in the main activity as shown in the picture below.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="@+id/textView"
android:layout_alignParentTop="true
"
android:layout_marginTop="44dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SurName"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_marginTop="44dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks"
android:id="@+id/textView3"
android:layout_below="@+id/textView2"
android:layout_marginTop="44dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View All"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:id="@+id/button_update"
android:layout_below="@+id/button"
android:layout_alignStart="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="@+id/button"
android:layout_marginTop="13dp"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2"
android:layout_marginLeft="18dp"
android:layout_marginStart="18dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:id="@+id/textView4"
android:layout_alignBaseline="@+id/editTextId
"
android:layout_alignBottom="@+id/editTextId"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView4"
android:layout_alignLeft="@+id/editTextId"
android:layout_alignStart="@+id/editTextId"></EditText>
</RelativeLayout>
Step 3 – Now create a new Java classes called Student.java and MyHelper.java.
You can see Project Structure of above image to know where to add this java classes.
Student.java
package com.myapplication;
/**
MyHelper.java
package com.myapplication;
/**
* Created by jaydeep on 27-Sep-17.
*/
import android.content.ContentValues;
import android.content.Context; import
android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME= "Student.db"; // DB Name
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("Create Table " + TABLE_NAME + " (ID INTEGER
PRIMARY KEY AUTOINCREMENT , NAME TEXT,
SURNAME TEXT, MARKS INTEGER) ");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
}
public boolean insertData(String name, String surname, String marks)
{
SQLiteDatabase db = this.getWritableDatabase(); // it will create DB & Table.
ContentValues contentValues = new ContentValues(); // It is used to put the values in the
Column.
contentValues.put(COl_2,name);
contentValues.put(COL_3,surname)
; contentValues.put(COL_4,marks);
long result =
db.insert(TABLE_NAME,null,contentValues); if (result
== -1)
return false;
else
return true;
}
MainActivity.java
package com.myapplication;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
addData();
viewAll();
updateData();
btnviewUpdate.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View view)
{
boolean isUpdate =
mh.updateData(editTextId.getText().toString(),editName.getText().toString(),editSurname.g
etText().toString(),editMarks.getText().toString());
if(isUpdate== true)
Toast.makeText(MainActivity.this,"Data Updated",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, " Data Not Updated "
,Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onClick(View view) {
boolean isInserted = mh.insertData(editName.getText().toString()
,editSurname.getText().toString(), editMarks.getText().toString());
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, " Data Not Inserted "
,Toast.LENGTH_LONG).show();
}
});
Thus we implement SQLite Application to Add and View and Update records.
FAQs:-
used for?
Computer Lab-X (BEIT 2015 Course) Page 63 of
108
Explain how Boolean values in SQLite are
SQLite?
Aim:
Design a smart light system which operates controls LED light automatically switched on in
evening and gets off in morning using Arduino, LED and LDR interface.
OBJECTIVES:
To design a smart light system which operates controls LED light automatically switched on in
evening and gets off in morning by programmable control of a dark resistance and bright
resistance of LDR (light dependent resistance) using Arduino IDE and UNO board.
THEORY :
An LDR is a component that has a (variable) resistance that changes with the light intensity that
falls upon it. See fig 1 and Fig 2 for LDR view and symbol. This allows them to be used in light
sensing circuits.
The most common type of LDR has a resistance that falls with an increase in the light intensity
falling upon the device (as shown in the image above). The resistance of an LDR may typically
for example one can observe the following resistances (this also depends on size of LDR and may
vary in your case):
You can therefore see that there is a large variation between these figures. If you plotted this
variation on a graph you would get something similar to that shown by the graph shown above.
Light dependent resistance (LDR) values shows different resistance values in dark and bright light
see Fig 4 which indicate same thing using graph. This can be observed just by measuring LDR
resistance on multimeter by exposing LDR to bright light and recording the value of resistance
and other case by holding it in dark. These two thresholds are deciding dark and bright resistance.
So if we want to put on LED in evening then on port where LED is connected need to put ON if
dark resistance value or greater than value is available on analog port where LDR is connected.
In else part or by excessively specifying bright resistance value one can put off LED by wring vice
vers statement for LED light port. One cam also observes the values on serial port by appropriate
statements. The connections are shown in fig 5.
1. First connect LDR to any analog port (out of any six) of Arduino UNO board.
2. Connect LED to any digital pin (out of any eleven) of Arduino UNO board.
3. Observe values on serial port
4. Write statements in of Arduino IDE as per specifying dark and bright resitance value to
put ON/OFF LED.
5. Hold LDR in palm and cover it by all fingers; this time LED need to glow. Now expose
LDR to light and see; LED need to turn off automatically.
6. By looking room light bright resistance; by turning ON and OFF of bulb / Tube light one
can see same effect on automatic LDE ON /OFF.
CONCLUSION : This way we make can use the open source platforms like Arduino Uno and
its IDE to make build smart lighting system based using properties of LDR sensor that controls
LED ON/OFF operation automatically by turning it ON in dark and turning it OFF in bright light.
FAQ :
1. What is LDR?
2. How LDR functions?
3. What is NTC and PTC and what is its significance in real world? Is it possible to
manage this from software to do vice versa operation of LDR?
4. Is it possible to control different 2 different LEDs connected to different digital pins of
Arduino on the basis of different dark and bright conditions of LDR? If ‘yes’ how? If
‘no’ why?
Aim:
Design and Develop a GUI for FAN regulator that uses Android platform.
Objective:
To develop a GUI for fan regulator which can be handled by android application.
Theory:
What is Android GUI:
User interface is everything that the user can see and interact with. Android
provides a variety of pre-built UI components such as structured layout objects and UI controls
that allow you to build the graphical user interface for your app. Android also provides other
UI modules for special interfaces such as dialogs, notifications, and menus.
Implementation:
MainActivity.java
package com.example.fan;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
ImageView imageView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.fanImage);
case (R.id.speed0):
System.out.println(R.id.speed0);
animation.setDuration(Integer.MAX_VALUE);
break;
case (R.id.speed1):
animation.setDuration(150);
break;
case (R.id.speed2):
animation.setDuration(100);
break;
case (R.id.speed3):
animation.setDuration(50);
break;
}
animation.setRepeatCount(Animation.INFINITE);
imageView.setAnimation(animation);
imageView.startAnimation(animation);
}
}
Acivity_main.xml
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="@+id/fanImage"
android:src="@drawable/fan1"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="150dp"
android:layout_marginBottom="150dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/speed0"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:onClick="changeSpeed"
android:text="0" />
<Button
android:id="@+id/speed1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:onClick="changeSpeed"
android:text="1" />
<Button
android:id="@+id/speed2"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
Computer Lab-X (BEIT 2015 Course) Page 71 of
108
android:onClick="changeSpeed"
android:text="2" />
<Button
android:id="@+id/speed3"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:onClick="changeSpeed"
android:text="3" />
</LinearLayout>
</RelativeLayout>
Rotate.xml
<rotate
android:toDegrees="75"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="200"
android:repeatMode="restart"
android:repeatCount="infinite"
/>
</set>
OUTPUT
Aim:
Design an Android based FAN regulator which operates controls Dynamic Fan Control using
NodeMUC ESP8266(wireless transceiver).
OBJECTIVES :
To design an Android based FAN regulator which operates controls Dynamic Fan Control
automatically using Android APP(BLYNK) by programmable control in Widget Box selecting
Slider using Arduino IDE and NodeMUC board.
THEORY :
A motor is an electrical machine which converts electrical energy into mechanical energy. The
principle of working of a DC motor is that "whenever a current carrying conductor is placed in
a magnetic field, it experiences a mechanical force". The direction of this force is given by
Fleming's left hand rule and its magnitude is given by F = BIL. Where, B = magnetic flux density,
I = current and L = length of the conductor within the magnetic field.
Fleming's left hand rule: If we stretch the first finger, second finger and thumb of our left hand
to be perpendicular to each other AND direction of magnetic field is represented by the first
finger, direction of the current is represented by second finger then the thumb represents the
direction of the force experienced by the current carrying conductor.
Above animation helps in understanding the
Working principle of a DC motor. When armature windings are connected to a DC supply,
current sets up in the winding. Magnetic field may be provided by field winding
(electromagnetism) or by using permanent magnets. In this case, current carrying armature
conductors experience force due to the magnetic field, according to the principle stated above.
Commutator is made segmented to achieve unidirectional torque. Otherwise, the direction of force
would have reversed every time when the direction of movement of conductor is reversed the
magnetic field.
FAQ :
1] Differentiate NodeMUC Vs Arduino UNO.
2] What is purpose of Rx and Tx pin in NodeMUC?
3] Is it possible to control 230V; 50Hz operated Fan? 4]
How relay operate?
Objective:
To design a wireless network for transferring data to a rolling display from computer.
Theory:
Wireless Scrolling Message Electronic Display Board is an embedded solution, by which one can
display the messages, received as SMS. Such displays can be kept in different parts of the city.
The public can send flash information from Mobiles or PCs to these displays for instant viewing.
Wireless Display Boards are designed with LED's to quickly display large amounts of
information in different bright colors - red, green and amber, resulting in great visual impact,
superior visibility, and high resolution. Any messages sent from a PC or mobiles will be displayed
in all the display Boards installed in any part of cities or country.
Benefits:
Application areas:
Advertisement Hoardings
At Railway Stations/Bus stops for displaying train/bus schedule
Instant update of Petrol Prices to all petrol Bunks from a Central office
Stock Tickers, which displays dynamically current value of the Stocks
Different Stalls, Multiplexes, Malls & Stores for displaying product ranges
Public information on local society
Current Prices of Commodities at different parts of the country
Other details:
Scrolling or Fixed Messages
Programmable Power On Default Message
Non Volatile messages stored capacity
Messages only From Authorized Mobile numbers
Display Messages as per schedule
Configurable through PC
Configurable through SMS
Programmable using SMS from Master
Single or Multi line Display
#include <LiquidCrystal.h>
LiquidCrystal lcd(13,12,5,4,3,2);
void setup() {
lcd.begin(16, 2);
lcd.print("Rolling Display Assignment !");
delay(1000);
}
void loop() {
for (int i = 0; i < 28; i++) {
lcd.scrollDisplayLeft();
delay(150);
}
Output:
OBJECTIVES:
To Acquire temperature values from 4 LM35 sensors and 1 DHT11 temperature+humidity sensor
in real time and transmit that data to the remote Arduino wirelessly using NRF24l01+ transceiver
modules and further give that data to PC via serial communication and analyze it using Machine
Learning in Python.
THEORY:
A] LM35 Sensor:
Applications:
Power Supplies
Battery Management
HVAC
Appliances
B] DHT11 Sensor:
DHT11 Temperature & Humidity Sensor features a temperature & humidity sensor complex with
a calibrated digital signal output. By using the exclusive digital-signal-acquisition technique and
temperature & humidity sensing technology, it ensures high reliability and excellent long-term
stability. This sensor includes a resistive-type humidity measurement component and an NTC
temperature measurement component, and connects to a high performance 8-bit microcontroller,
offering excellent quality, fast response, anti-interference ability and cost- effectiveness.
Features of DHT11 are as follows:
Operating Voltage: 3.5V to 5.5V
The nRF24L01+ is a single chip 2.4GHz transceiver with an embedded baseband protocol engine,
suitable for ultra-low power wireless applications. The nRF24L01+ is designed for operations in
the world-wide ISM frequency band at 2.4-2.4835GHz. To design a radio system with the
nRF24L01+, you simply need an MCU and a few external passive components. One can operate
and configure the NRF24L01+ through a Serial Peripheral Interface (SPI). The register map, which
is accessible through the SPI, contains all configuration registers in the nRF24L01+ and is
accessible in all operation modes of the chip.
Features of nRF24L01+ are as follows:
World Wide 2.4GHz ISM band Operation
1 to 32 bytes dynamic payload size per packet
Integrated voltage regulator
1.9V to 3.6V Supply Range
250kbps, 1 and 2 Mbps air data rate
D] Machine Learning:
Machine learning is an application of artificial intelligence (AI) that provides systems the
ability to automatically learn and improve from experience without being explicitly
programmed.
Machine learning focuses on the development of computer programs that can access data and
use it learn for themselves.
The process of learning begins with observations or data, such as examples, direct experience,
or instruction, in order to look for patterns in data and make better decisions in the future based
on the examples that we provide. The primary aim is to allow the computers learn
automatically without human intervention or assistance and adjust actions accordingly.
Machine learning enables analysis of massive quantities of data. While it generally delivers
faster, more accurate results in order to identify profitable opportunities or dangerous risks, it
may also require additional time and resources to train it properly. Combining machine learning
with AI and cognitive technologies can make it even more effective in processing large volumes
of information.
Support Vector Machine:
A Support Vector Machine models the situation by creating a feature space, which is a finite-
dimensional vector space, each dimension of which represents a "feature" of a particular object. In
the context of spam or document classification, each "feature" is the prevalence or importance of
a particular word. The goal of the SVM is to train a model that assigns new unseen objects into a
particular category. It achieves this by creating a linear partition of the feature space into two
categories. Based on the features in the new unseen objects (e.g. documents/emails), it places an
object "above" or "below" the separation plane, leading to a categorisation (e.g. spam or non-
spam). This makes it an example of a non-probabilistic linear classifier. It is non-probabilistic,
because the features in the new objects fully determine its location in feature space and there is
no stochastic element involved.
Procedure:
CONCLUSION :
This way we make can use of the open source platforms like Arduino and Python to make our
own data and use for machine learning applications in real time without any limitations. The
sensors can be varied and different machine learning training algorithms can be implemented
for higher accuracy and performance.
FAQ :
1. 1What is the drawback of LM35 sensor?
2. 2What is the limitation of DHT11 sensor?
3. 3Why use nRF24L01+, when we have Bluetooth and XBEE modules?
Computer Lab-X (BEIT 2015 Course) Page 87 of
108
What are the advantages and disadvantages?
4. What is machine learning? Why do we use it solve real world problems?
Compare with classical approach.