17CAU304A Android Programming 3H - 3C Marks: 40 60 100 Scope
17CAU304A Android Programming 3H - 3C Marks: 40 60 100 Scope
(Deemed to be University)
(Established Under Section 3 of UGC Act, 1956)
Coimbatore-21
Faculty of Arts , Science and Humanities
Scope
This is an introductory Android programming course designed to introduce and familiarize
participants with programming in the Android environment.
Objectives
To explain the differences between Android and other mobile development environments.
teach students to design, create, deploy, and test applications for the Android mobile
phone platform.
introduce students to the most common tools and techniques for writing Android
applications.
to explain how Android applications work, their life cycle, manifest, Intents, and using
external resources.
to teach to access and work with databases under android OS
design and develop useful Android applications with compelling user. interfaces .by
using, extending, and creating your own layouts and Views and using Menus.
Unit-I
Introduction: History of Android, Introduction to Android Operating Systems, Android
Development Tools, Android Architecture. (2L)
Unit-II
Overview of object oriented programming using Java: OOPs Concepts: Inheritance,
Polymorphism, Interfaces, Abstract class, Threads, Overloading and Overriding, Java Virtual
Machine. (4L)
Unit-III
Development Tools: Installing and using Eclipse with ADT plug-in, Installing Virtual machine
for Android sandwich/Jelly bean (Emulator), configuring the installed tools, creating a android
project– Hello Word, run on emulator, Deploy it on USB-connected Android device. (5L)
Unit-IV
User Interface Architecture: Application context, intents, Activity life cycle, multiple screen size
s.(2L) User Interface Design: Form widgets, Text Fields, Layouts, Button control, toggle buttons,
Spinners(Combo boxes),Images, Menu, Dialog.(2L)
Semester – III
17CAU304A ANDROID PROGRAMMING 3H – 3C
Unit-V
Database: Understanding of SQL database, connecting with the database. (2L)
Suggested readings
1. James C.Sheusi,(2013). Android application development for Java for Java
programmers, Cengage Learning.
Websites
1. http://www.developer.android.com
2. http://developer.android.com/about/versions/index.html
3. http://developer.android.com/training/basics/firstapp/index.html
4. http://developer.android.com/guide/components/activities.html
5. http://developer.android.com/guide/components/fundamentals.html
6. http://developer.android.com/guide/components/intents-filters.html.
7. http://developer.android.com/training/multiscreen/screensizes.html
8. http://developer.android.com/guide/topics/ui/controls.html
9. http://developer.android.com/guide/topics/ui/declaring-layout.html
10. http://developer.android.com/training/basics/data-storage/databases.html
KarpagamAcademy of Higher Education
(Established Under Section 3 of UGC Act 1956)
Eachanari Post, Coimbatore – 641 021. INDIA
Phone : 0422-2611146, 2611082 Fax No : 0422 -2611043
4 1 Android Architecture W2
TEXT BOOK:
T1: James C. Sheusi (2013), Android Application development for java Programmers, Cengage
Learning.
WEBSITES
W1:http://www.developer.android.com
W2: www.androidauthority.com
LECTURE PLAN
S.No Lecturer Topics to be Covered Support Materials
Duration(Hrs)
UNIT II
1 1 Oops Concepts: Inheritance W3
2 1 Polymorphism T1:65-66
3 1 Interfaces T1:66-67
5 1 Threads T1:70-72
TEXT BOOK:
T1: James C. Sheusi (2013), Android Application development for java Programmers, Cengage
Learning.
WEBSITES
W3:http://developer.android.com/guide/components/activities.html
W4:http://developer.android.com/funcanmentals.html
S.No Lecturer Topics to be Covered Support Materials
Duration(Hrs)
UNIT III
1 1 Installing and using Eclipse with ADT plug-in T1:1-4,W4
TEXT BOOK
T1: James C.Sheusi,(2013). Android application development for Java for Java programmers, Cengage
Learning.
WEBSITES
W6:http://developer.android.com/training
W7:http://developer.android.com/screensize.html
LECTURE PLAN
S.No Lecturer Topics to be Covered Support Materials
Duration(Hrs)
UNIT V
1 1 Understanding of SQL Database T1:197-198,W8
TEXT BOOK
T1: James C.Sheusi,(2013). Android application development for Java for Java programmers, Cengage
Learning.
WEBSITES
W8:http://developer.android.com/training/basics/data.storage/databases.html
JOURNALS:
J1: ”Creating and using Database for Android”, Int. Journal of Database theory and applications, Vol 5, 2012.
UNIT I ANDROID PROGRAMMING BCA (2017-2020) BATCH
History of Android
The history and versions of android are interesting to know. The code names of android
ranges from A to J currently, such
as Aestro, Blender, Cupcake, Donut, Eclair, Froyo,Gingerbread, Honeycomb, Ice Cream
Sandwitch, Jelly Bean, KitKat and Lollipop. Let's understand the android history in a
sequence.
1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States
in October, 2003.
2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary
of Google Incorporation.
3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris
White andNick Sears.
4) Originally intended for camera but shifted to smart phones later because of low market for
camera only.
5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots.
Let's see the android versions, codenames and API Level provided by Google.
1.5 Cupcake 3
1.6 Donut 4
2.1 Eclair 7
2.2 Froyo 8
4.4 KitKat 19
5.0 Lollipop 21
Android is a mobile operating system developed by Google, based on the Linux kernel and
designed primarily for touchscreen mobile devices such as smartphones and tablets.
Android's user interface is mainly based on direct manipulation, using touch gestures that loosely
correspond to real-world actions, such as swiping, tapping and pinching, to manipulate on-screen
objects, along with a virtual keyboard for text input. In addition to touchscreen devices, Google
has further developed Android TV for televisions, Android Auto for cars, and Android Wear for
wrist watches, each with a specialized user interface. Variants of Android are also used
on notebooks,game consoles, digital cameras, and other electronics.
Initially developed by Android Inc., which Google bought in 2005, Android was unveiled in
2007, along with the founding of the Open Handset Alliance – a consortium
of hardware, software, and telecommunication companies devoted to advancing open
standardsfor mobile devices.
Beginning with the first commercial Android device in September 2008, the operating system
has gone through multiple major releases, with the current version being 7.0 "Nougat", released
in August 2016. Android applications ("apps") can be downloaded from the Google Play store,
which features over 2.7 million apps as of February 2017. Android has been the best-selling OS
on tablets since 2013, and runs on the vast majority[a] of smartphones. As of May 2017, Android
has two billion monthly active users, and it has the largest installed base of any operating system.
Android's source code is released by Google under an open source license, although most
Android devices ultimately ship with a combination of free and open
source and proprietary software, including proprietary software required for accessing Google
services. Android is popular with technology companies that require a ready-made, low-cost and
customizable operating system for high-tech devices. Its open nature has encouraged a large
community of developers and enthusiasts to use the open-source code as a foundation for
community-driven projects, which deliver updates to older devices, add new features for
advanced users or bring Android to devices originally shipped with other operating systems.
The extensive variation of hardware in Android devices causes significant delays for software
upgrades, with new versions of the operating system and security patches typically taking
months before reaching consumers, or sometimes not at all. The success of Android has made it
a target for patent and copyright litigation as part of the so-called "smartphone wars" between
technology companies.
Android software development is the process by which new applications are created for
the Android operating system. Applications are usually developed inJava programming language
using the Android software development kit (SDK), but other development environments are
also available.
The Android software development kit (SDK) includes a comprehensive set of development
tools.[4] These include a debugger, libraries, a handset emulatorbased on QEMU, documentation,
sample code, and tutorials. Currently supported development platforms include computers
running Linux (any modern desktop Linux distribution), Mac OS X 10.5.8 or later, and Windows
7or later. As of March 2015, the SDK is not available on Android itself, but software
development is possible by using specialized Android applications.
Until around the end of 2014, the officially supported integrated development environment (IDE)
was Eclipse using the Android Development Tools (ADT) Plugin, though IntelliJ IDEA IDE (all
editions) fully supports Android development out of the box,[8] and NetBeans IDE also supports
Android development via a plugin.[9] As of 2015, Android Studio,[10] made by Google and
powered by IntelliJ, is the official IDE; however, developers are free to use others, but Google
made it clear that ADT was officially deprecated since the end of 2015 to focus on Android
Studio as the official Android IDE.[11] Additionally, developers may use any text editor to edit
Java and XML files, then use command line tools (Java Development Kit and Apache Ant are
required) to create, build and debug Android applications as well as control attached Android
devices (e.g., triggering a reboot, installing software package(s) remotely).
Enhancements to Android's SDK go hand in hand with the overall Android platform
development. The SDK also supports older versions of the Android platform in case developers
wish to target their applications at older devices. Development tools are downloadable
components, so after one has downloaded the latest version and platform, older platforms and
tools can also be downloaded for compatibility testing.
Android applications are packaged in .apk format and stored under /data/app folder on the
Android OS (the folder is accessible only to the root user for security reasons). APK package
contains .dex files[14] (compiled byte code files calledDalvik executables), resource files, etc.
Android Debug Bridge
The Android Debug Bridge (ADB) is a toolkit included in the Android SDK package. It consists
of both client and server-side programs that communicate with one another. The ADB is
typically accessed through the command-line interface,[15]although numerous graphical user
interfaces exist to control ADB.
Fastboot.
Fastboot is a diagnostic protocol included with the SDK package used primarily to modify
the flash filesystem via a USBconnection from host computer. It requires that the device be
started in a boot loader or Secondary Program Loader mode, in which only the most basic
hardware initialization is performed. After enabling the protocol on the device itself, it will
accept a specific set of commands sent to it via USB using a command line. Some of the most
commonly used fastboot commands include:
flash – rewrites a partition with a binary image stored on the host computer
erase – erases a specific partition
reboot – reboots the device into either the main operating system, the system recovery
partition or back into its boot loader
devices – displays a list of all devices (with the serial number) connected to the host
computer
format – formats a specific partition; the file system of the partition must be recognized
by the device
ANDROID NDK
Libraries written in C/C++ can be compiled to ARM, MIPS or x86 native code(or their 64-bit
variants) and installed using the Android Native Development Kit (NDK). These native libraries
can be called from Java code running under the Dalvik VM using the System.loadLibrary call,
which is part of the standard Android Java classes.
Complete applications can be compiled and installed using traditional development
tools.[21] However, according to the Android documentation, NDK should not be used solely
because the developer prefers to program in C/C++, as using NDK increases complexity while
most applications would not benefit from using it.
The [23]ADB Debugger gives a root shell under the Android Emulator which allows ARM, MIPS
or x86 native code to be uploaded and executed. Native code can be compiled
using Clang or GCC on a standard PC. Running native code is complicated by Android's use of a
non-standard C library (libc, known as Bionic).
It is possible to use the Android Studio with Gradle to develop NDK projects.[26] Other third-
party tools allow integrating the NDK into Eclipse[27] and Visual Studio.
Android Open Accessory Development Kit
The Android 3.1 platform (also backported to Android 2.3.4) introduces Android Open
Accessory support, which allows external USB hardware (an Android USB accessory) to interact
with an Android-powered device in a special "accessory" mode. When an Android-powered
device is in accessory mode, the connected accessory acts as the USB host (powers the bus and
enumerates devices) and the Android-powered device acts as the USB device. Android USB
accessories are specifically designed to attach to Android-powered devices and adhere to a
simple protocol (Android accessory protocol) that allows them to detect Android-powered
devices that support accessory mode.
Another built-in Android development tool, the Android Device Monitor allows you to monitor your
device or virtual device during runtime and get access to information such as how many processes
are running on what thread, network stats, the LogCat and more.
ANDROID Architecture
Android is an open source, Linux-based software stack created for a wide array of devices and
form factors. The following diagram shows the major components of the Android platform.
The foundation of the Android platform is the Linux kernel. For example, the Android Runtime
(ART) relies on the Linux kernel for underlying functionalities such as threading and low-level
memory management.
Using a Linux kernel allows Android to take advantage of key security features and allows
device manufacturers to develop hardware drivers for a well-known kernel.
The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware
capabilities to the higher-level Java API framework. The HAL consists of multiple library
modules, each of which implements an interface for a specific type of hardware component, such
as the camera or bluetooth module. When a framework API makes a call to access device
hardware, the Android system loads the library module for that hardware component.
Android Runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its own
process and with its own instance of the Android Runtime (ART). ART is written to run multiple
virtual machines on low-memory devices by executing DEX files, a bytecode format designed
specially for Android that's optimized for minimal memory footprint. Build toolchains, such
as Jack, compile Java sources into DEX bytecode, which can run on the Android platform.
Prior to Android version 5.0 (API level 21), Dalvik was the Android runtime. If your app runs
well on ART, then it should work on Dalvik as well, but the reverse may not be true.
Android also includes a set of core runtime libraries that provide most of the functionality of the
Java programming language, including some Java 8 language features, that the Java API
framework uses.
If you are developing an app that requires C or C++ code, you can use the Android NDK to
access some of thesenative platform libraries directly from your native code.
A rich and extensible View System you can use to build an app’s UI, including lists,
grids, text boxes, buttons, and even an embeddable web browser
A Notification Manager that enables all apps to display custom alerts in the status bar
Content Providers that enable apps to access data from other apps, such as the Contacts
app, or to share their own data
Developers have full access to the same framework APIs that Android system apps use.
System Apps
Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing,
contacts, and more. Apps included with the platform have no special status among the apps the
user chooses to install. So a third-party app can become the user's default web browser, SSMS
messenger, or even the default keyboard (some exceptions apply, such as the system's Settings
app).
The system apps function both as apps for users and to provide key capabilities that developers
can access from their own app. For example, if your app would like to deliver an SMS message,
you don't need to build that functionality yourself—you can instead invoke whichever SMS app
is already installed to deliver a message to the recipient you specify.
PART-B
Two mark Questions
1. What is an Android Operating System?
2. What is object oriented programming?
3. State IDE.
4. Define CheckBox.
5. What is meant by database?
PART-C
8 Mark Questions
1. Explain the history of Android.
2.Discuss the architecture of Android.
3.Explain Android Development Tools (ADT). .
4.Discuss Android SDK.
5.Discuss Android operating system.
6.Explain the architecture of Android.
7.Explain the version, code name and API level of android.
8.Explain Android open accessory development kit.
9.Explain Linux kernel.
10.Discuss Java API framework.
Eclipse is used to execute Java and Java and Java and Java and Java and
_______ programs. C Oracle Android VB.Net Android
ADT stands for __________. Android Android Abstract Abstract Android
Design Develop Design Develop Developme
Tool ment Tool ment nt Tool
Tool Tool
Which year Google acquired 2004 2003 2005 2006 2003
Android Incorporation?
Which company first launched HTC STC YTC MTC HTC
Android Mobile?
Android version 1.5 is called CupCake CupBun Cloud Ice Cloudy CupCake
as ______________ Coffee
Donut is the 1.5 1.7 1.6 1.8 1.6
__________Android version.
Android version 1.5 is called Exclarie CupBun Choclate Eclair Eclair
as ______________
Froyo is the ________ Android 2.4 2.2 2.3 2.6 2.2
version.
Android version 2.3 is called GingerBa GingerTe Gingerco Gingerbr Gingerbre
as ______________ ke a ffee ead ad
Android version 3.1 and 3.3 HONYW Honeyco HoneyDa Honeybo Honeycom
are called as ______________ ELL mb tes ttle b
Android version 4.0 is called Icecream Vannila Ice cream Icebar Ice cream
as ___________. Ice Sandwitc Sandwitch
h
Android version 4.1,4,2 and Jellyfish Jelly Jellyice Jellysuga Jelly Bean
4.3 are called as ___________. Bean r
Unit-II Syllabus
Overview of object oriented programming using Java: OOPs Concepts: Inheritance-
Polymorphism-Interfaces-Abstract class-Threads-Overloading and Overriding-Java Virtual
Machine. (4L)
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Inheritance
Benefits of inheritance
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new
class is called child or subclass.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Output:
playing...
barking...
Output:
weeping...
barking...
eating...
Output:
sleeping...
eating...
Polymorphism
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
Method Overloading:
In Java, it is possible to define two or more methods of same name in a class, provided that there
argument list or parameters are different. This concept is known as Method Overloading.
Example:
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Method Overriding
Child class has the same method as of base class. In such cases child class overrides the parent
class method without even touching the source code of the base class. This feature is known as
method overriding.
Example:
Java interfaces are like Java classes but they contain only static final constants and declaration of
methods. Methods are not defined and classes which implements an interface must define the
body of method(s) of interface(s). Final constants can't be modified once they are initialized;
final, interface, extend and implements are Java keywords.
Declaration of interface:
interface InterfaceName {
// constants declaration
// methods declaration
}
interface Info {
static final String language = "Java";
public void display();
}
Java is awesome
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
running safely..
Threads
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
System.out.println("thread is running...");
t1.start();
Output:
thread is running...
System.out.println("thread is running...");
t1.start();
Output:
thread is running...
Priority of a Thread
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority.
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to
run a Java program. There are three notions of the JVM: specification, implementation, and
instance. The specification is a document that formally describes what is required of a JVM
implementation. Having a single specification ensures all implementations are interoperable. A
JVM implementation is a computer program that meets the requirements of the JVM
specification. An instance of a JVM is an implementation running in a process that executes a
computer program compiled into Java bytecode.
Java Runtime Environment (JRE) is a software package that contains what is required to run a
Java program. It includes a Java Virtual Machine implementation together with an
implementation of the Java Class Library. The Oracle Corporation, which owns the Java
trademark, distributes a Java Runtime environment with their Java Virtual Machine called
HotSpot.
Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javac compiler. The Java Development Kit is provided free of charge either by Oracle
Corporation directly, or by the OpenJDK open source project, which is governed by Oracle.
JVM specification
The Java virtual machine is an abstract (virtual) computer defined by a specification. This
specification omits implementation details that are not essential to ensure interoperability: the
memory layout of run-time data areas, the garbage-collection algorithm used, and any internal
optimization of the Java virtual machine instructions (their translation into machine code). The
main reason for this omission is to not unnecessarily constrain implementers. Any Java
application can be run only inside some concrete implementation of the abstract specification of
the Java virtual machine.[1]
Starting with Java Platform, Standard Edition (J2SE) 5.0, changes to the JVM specification have
been developed under the Java Community Process as JSR 924. As of 2006, changes to
specification to support changes proposed to the class file format (JSR 202) are being done as a
maintenance release of JSR 924. The specification for the JVM was published as the blue book,
The preface states:
We intend that this specification should sufficiently document the Java Virtual Machine to make
possible compatible clean-room implementations. Oracle provides tests that verify the proper
operation of implementations of the Java Virtual Machine.
One of Oracle's JVMs is named HotSpot, the other, inherited from BEA Systems is JRockit.
Clean-room Java implementations include Kaffe and IBM J9. Oracle owns the Java trademark
and may allow its use to certify implementation suites as fully compatible with Oracle's
specification.
Class loader
One of the organizational units of JVM byte code is a class. A class loader implementation must
be able to recognize and load anything that conforms to the Java class file format. Any
implementation is free to recognize other binary forms besides class files, but it must recognize
class files.
The class loader performs three basic activities in this strict order:
JVM languages
A JVM language is any language with functionality that can be expressed in terms of a
valid class file which can be hosted by the Java Virtual Machine. A class file contains
Java Virtual Machine instructions (Java byte code) and a symbol table, as well as other
ancillary information. The class file format is the hardware- and operating system-
independent binary format used to represent compiled classes and interfaces.
There are several JVM languages, both old languages ported to JVM and completely new
languages. JRuby and Jython are perhaps the most well-known ports of existing
languages, i.e. Ruby and Python respectively. Of the new languages that have been
created from scratch to compile to Java bytecode, Clojure, Groovy and Scala may be the
most popular ones. A notable feature with the JVM languages is that they are compatible
with each other, so that, for example, Scala libraries can be used with Java programs and
vice versa.
Java 7 JVM implements JSR 292: Supporting Dynamically Typed Languages on the Java
Platform, a new feature which supports dynamically typed languages in the JVM. This
feature is developed within the Da Vinci Machine project whose mission is to extend the
JVM so that it supports languages other than Java
PART-B
Two mark Questions
PART-C
Eight Mark Questions
1.Discuss the concepts of OOPs in Java.
2.Explain the concept of inheritance and its types.
3. Explain multilevel inheritance in Java with suitable program.
4.Discuss the concept of method overloading in java.
5. Explain the concept of Method overriding with an example Java program.
6. Discuss Abstract class with an example Java program.
7.Explain interface in Java with an example Java program.
8. Discuss the Multi threading concept with an example Java program.
9.Explain various life cycles and priorities of thread.
10. Discuss Java virtual machine.
Unit-II Syllabus
Overview of object oriented programming using Java: OOPs Concepts: Inheritance-
Polymorphism-Interfaces-Abstract class-Threads-Overloading and Overriding-Java Virtual
Machine. (4L)
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Inheritance
Benefits of inheritance
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new
class is called child or subclass.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Output:
playing...
barking...
Output:
weeping...
barking...
eating...
Output:
sleeping...
eating...
Polymorphism
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
Method Overloading:
In Java, it is possible to define two or more methods of same name in a class, provided that there
argument list or parameters are different. This concept is known as Method Overloading.
Example:
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Method Overriding
Child class has the same method as of base class. In such cases child class overrides the parent
class method without even touching the source code of the base class. This feature is known as
method overriding.
Example:
Java interfaces are like Java classes but they contain only static final constants and declaration of
methods. Methods are not defined and classes which implements an interface must define the
body of method(s) of interface(s). Final constants can't be modified once they are initialized;
final, interface, extend and implements are Java keywords.
Declaration of interface:
interface InterfaceName {
// constants declaration
// methods declaration
}
interface Info {
static final String language = "Java";
public void display();
}
Java is awesome
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
running safely..
Threads
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
System.out.println("thread is running...");
t1.start();
Output:
thread is running...
System.out.println("thread is running...");
t1.start();
Output:
thread is running...
Priority of a Thread
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority.
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to
run a Java program. There are three notions of the JVM: specification, implementation, and
instance. The specification is a document that formally describes what is required of a JVM
implementation. Having a single specification ensures all implementations are interoperable. A
JVM implementation is a computer program that meets the requirements of the JVM
specification. An instance of a JVM is an implementation running in a process that executes a
computer program compiled into Java bytecode.
Java Runtime Environment (JRE) is a software package that contains what is required to run a
Java program. It includes a Java Virtual Machine implementation together with an
implementation of the Java Class Library. The Oracle Corporation, which owns the Java
trademark, distributes a Java Runtime environment with their Java Virtual Machine called
HotSpot.
Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javac compiler. The Java Development Kit is provided free of charge either by Oracle
Corporation directly, or by the OpenJDK open source project, which is governed by Oracle.
JVM specification
The Java virtual machine is an abstract (virtual) computer defined by a specification. This
specification omits implementation details that are not essential to ensure interoperability: the
memory layout of run-time data areas, the garbage-collection algorithm used, and any internal
optimization of the Java virtual machine instructions (their translation into machine code). The
main reason for this omission is to not unnecessarily constrain implementers. Any Java
application can be run only inside some concrete implementation of the abstract specification of
the Java virtual machine.[1]
Starting with Java Platform, Standard Edition (J2SE) 5.0, changes to the JVM specification have
been developed under the Java Community Process as JSR 924. As of 2006, changes to
specification to support changes proposed to the class file format (JSR 202) are being done as a
maintenance release of JSR 924. The specification for the JVM was published as the blue book,
The preface states:
We intend that this specification should sufficiently document the Java Virtual Machine to make
possible compatible clean-room implementations. Oracle provides tests that verify the proper
operation of implementations of the Java Virtual Machine.
One of Oracle's JVMs is named HotSpot, the other, inherited from BEA Systems is JRockit.
Clean-room Java implementations include Kaffe and IBM J9. Oracle owns the Java trademark
and may allow its use to certify implementation suites as fully compatible with Oracle's
specification.
Class loader
One of the organizational units of JVM byte code is a class. A class loader implementation must
be able to recognize and load anything that conforms to the Java class file format. Any
implementation is free to recognize other binary forms besides class files, but it must recognize
class files.
The class loader performs three basic activities in this strict order:
JVM languages
A JVM language is any language with functionality that can be expressed in terms of a
valid class file which can be hosted by the Java Virtual Machine. A class file contains
Java Virtual Machine instructions (Java byte code) and a symbol table, as well as other
ancillary information. The class file format is the hardware- and operating system-
independent binary format used to represent compiled classes and interfaces.
There are several JVM languages, both old languages ported to JVM and completely new
languages. JRuby and Jython are perhaps the most well-known ports of existing
languages, i.e. Ruby and Python respectively. Of the new languages that have been
created from scratch to compile to Java bytecode, Clojure, Groovy and Scala may be the
most popular ones. A notable feature with the JVM languages is that they are compatible
with each other, so that, for example, Scala libraries can be used with Java programs and
vice versa.
Java 7 JVM implements JSR 292: Supporting Dynamically Typed Languages on the Java
Platform, a new feature which supports dynamically typed languages in the JVM. This
feature is developed within the Da Vinci Machine project whose mission is to extend the
JVM so that it supports languages other than Java
PART-B
Two mark Questions
PART-C
Eight Mark Questions
1.Discuss the concepts of OOPs in Java.
2.Explain the concept of inheritance and its types.
3. Explain multilevel inheritance in Java with suitable program.
4.Discuss the concept of method overloading in java.
5. Explain the concept of Method overriding with an example Java program.
6. Discuss Abstract class with an example Java program.
7.Explain interface in Java with an example Java program.
8. Discuss the Multi threading concept with an example Java program.
9.Explain various life cycles and priorities of thread.
10. Discuss Java virtual machine.
Android offers a custom plugin for the Eclipse IDE, called Android Development Tools
(ADT). This plugin provides a powerful, integrated environment in which to develop
Android apps. It extends the capabilities of Eclipse to let you quickly set up new Android
projects, build an app UI, debug your app, and export signed (or unsigned) app packages
(APKs) for distribution.
https://dl-ssl.google.com/android/eclipse/
4. Click OK.
If you have trouble acquiring the plugin, try using "http" in the Location URL,
instead of "https" (https is preferred for security reasons).
5. In the Available Software dialog, select the checkbox next to Developer Tools
and click Next.
6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
7. Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the
software can't be established, click OK.
Once Eclipse restarts, you must specify the location of your Android SDK directory:
Your Eclipse IDE is now set up to develop Android apps, but you need to add the latest
SDK platform tools and an Android platform to your environment. To get these packages
for your SDK, continue to Adding Platforms and Packages.
Troubleshooting Installation
If you are having trouble downloading the ADT plugin after following the steps above,
here are some suggestions:
If Eclipse can not find the remote update site containing the ADT plugin, try
changing the remote site URL to use http, rather than https. That is, set the
Location for the remote site to:
http://dl-ssl.google.com/android/eclipse/
If you are behind a firewall (such as a corporate firewall), make sure that you
have properly configured your proxy settings in Eclipse. In Eclipse, you can
configure proxy information from the main Eclipse menu in Window (on Mac OS
X, Eclipse) > Preferences > General > Network Connections.
If you are still unable to use Eclipse to download the ADT plugin as a remote update site,
you can download the ADT zip file to your local machine and manually install it:
1. Download the ADT Plugin zip file (do not unpack it):
If you get a security warning saying that the authenticity or validity of the
software can't be established, click OK.
Android is Linux based open source operating system, especially designed for touch
based smart phones and tablets and is one of the most widely used operating system by
Mobile phone and tablets manufacturers. As Android OS only supports ARM architecture
based hardware so you can't run it on x86 architecture i.e. Computer or laptop. In order to
run it on x86 architecture, you need to have an Android OS which supports x86
architecture luckily Android x86 project provides it for various testing purposes and you
can install Android OS along with your Windows Vista, 7 & 8 operating system.
As I am using Microsoft Windows 8 OS thus I have mentioned the steps for installing
Android OS on Virtual PC along with Windows 8(learn how to install Windows 8 on
virtual PC) but these steps are very much applicable to Windows Vista and 7.
- Now visit android-x86.org site and head over to download page. If your system name is
listed then download the Android OS ISO image from the respective link else download
the ISO image especially created for x86 architecture based hardware which will work on
every system (from here
https://docs.google.com/open?id=0B4GbJReHMmu_amMzQzJoNGw3WFU). Also if
you experience internet connectivity and audio problem with ISO image downloaded for
respective system then download the generic ISO image from link given above
- Now open Oracle VM VirtualBox and press CTRL + N for creating a new Virtual
Machine and also click the Hide Description button to make visible the hidden Hard drive
options
- In name box write Android ICS or it could be anything which helps you to recognize it
easily, in Type box select Linux option and in Version choose Linux 2.6 respectively
- Under Memory size option increase the slider to 512 MB for better performance though
you can assign higher or lower memory than this
- In Hard drive option make sure "Create a virtual hard drive now" is selected, Click
Create button
This will create the virtual machine named Android ICS. Now you have to modify few
options to optimize it for better performance. Open settings Window, navigate to System
tab then to Processor tab and tick the check box against the "Enable PAE/NX" option.
Now navigate to display tab and increase the video memory size to more than 10 MB and
enable the 3D acceleration under extended feature.
On Android –x86 Installation Window, select the "Installation – Install Android –x86 to
harddisk option". It will initiate the process of installing Android OS
Set the RAM size to more than 512MB. I configured 1GB. Create a new hard disk.
4) Go to the settings of virtual machine and edit the storage settings. We need to browse
and mount the ISO file which was downloaded from Google site, to IDE controller of
CD/DVD drive.
The CD/DVD drive should appear as shown above after loading the ISO.
5) Power on VM which will boot from attached ISO. Select the installation option as
below.
Make it as ‘Primary’ in next screen and press Enter to allocate full size for the partition.
9) Once you have come out of partition creation tool, you can chose the newly created
partition to start the installation on VirtualBox.
Press ‘Yes’ to format the partition. Also select ‘Yes’ to install boot loader GRUB. Again
‘Yes’ to install /System directory as read-write in next screen.
11) We have successfully install Android 4.3 on Windows 8 with VirtualBox. Reboot the
virtual machine to use.
Note – Remove the ISO file from CD/DVD drive before booting, otherwise it will again
boot from ISO and start installation process.
12) Once virtual machine is booted, it is better to disable mouse integration with VM. So,
it will be easy to access and use mouse inside Android OS.
13) Network worked directly in bridge mode inside virtual machine. Performance of
graphics is not up the the standard. Do not think to play Android games inside this virtual
machine, it will not work. But still it is worth to install and play around with it without
having a real phone or tablet device.
Here are some of the screenshots taken from Jelly Bean virtual machine in Windows 8.
To create a simple Hello World Android project can be done either with Eclipse
or Android Studio. Here I am going to explain how it can be created by using Android
Studio 0.8.0.
Android Studio:
http://tools.android.com/download/studio/beta
Pre-requisite:
https://www.codeproject.com/KB/android/803646/SDKManager.png
https://www.codeproject.com/KB/android/803646/NewProject.png
Enter the application and company domain and select the project location as shown
below and click on Next button.
https://www.codeproject.com/KB/Android/803646/Configure.png
Select the appropriate minimum version of android we are going to target as shown in the
list as below
https://www.codeproject.com/KB/android/803646/formfactor.png
Select the template need as pre requirement. I have selected the blank activity.
https://www.codeproject.com/KB/Android/803646/Activity.png
https://www.codeproject.com/KB/Android/803646/ActivityName.png
Click on the finish button. The project gets created and will be shown as below
https://www.codeproject.com/KB/Android/803646/FinishNavigation.png
Files / Components
Important files and directory of Android project to be known and their purpose
1. src - This contains the .java source files for your project. By default, it includes an
MainActivity.java source file having an activity class that runs when your app is
launched using the app icon.
2. generated - This contains the .R file, a compiler-generated file that references all
the resources found in your project. You should not modify this file
3. bin - This folder contains the Android package files .apk built by the ADT during
the build process and everything else needed to run an Android application.
4. res/drawable-hdpi - This is a directory for drawable objects that are designed for
high-density screens.
5. res/layout - This is a directory for files that define your app's user interface.
6. res/values - This is a directory for other various XML files that contain a
collection of resources, such as strings and colors definitions.
7. AndroidManifest.xml - This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
https://www.codeproject.com/KB/Android/803646/filecomponents.png
String file
The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types
of strings go into this file. This file is responsible for their textual content. For example, a
default strings file will look like as following file
R file
The gen/myapps.helloworld/R.java file is the glue between the activity Java files like
Main.java and the resources like strings.xml. It is an automatically generated file and you
should not modify the content of the R.java file. Following is a sample of R.java
filehttps://www.codeproject.com/KB/Android/803646/rfile.png
Layout File
to change the layout of your application. For your "Hello World!" application, this file
will have following content related to default layout
Text Mode
https://www.codeproject.com/KB/Android/803646/Layouttext.png
Layout Design
https://www.codeproject.com/KB/Android/803646/layoutdesign.png
Emulator takes more time to load so before running app we should start emulator.
Emulator can be started from SDK manager tools Manage AVDs.
https://www.codeproject.com/KB/Android/803646/SDKManager.pngAVD Manager
Create the AVD and click on the start to run the emulator
https://www.codeproject.com/KB/Android/803646/AVDmanagers.png
https://www.codeproject.com/KB/Android/803646/Emulator.png
Pre-requisite
Generate a signed APK from the Android Studio under Build / generate signed
APK.
Steps
PART-B
Two mark Questions
PART-C
EIGHT MARK QUESTIONS
Unit-4 Notes
Syllabus
User Interface Architecture: Application context-intents-Activity life cycle-multiple
screen sizes.(2L) User Interface Design: Form widgets-Text Fields-Layouts-Button
control-toggle buttons-Spinners(Combo boxes)-Images-Menu-Dialog.(2L
The Activity class defines the following call backs i.e. events. You don't need to
implement all the callbacks methods. However, it's important that you understand each
one and implement those that ensure your app behaves the way users expect.
4 The paused activity does not receive user input and cannot execute any code and
called when the current activity is being paused and the previous activity is being
resumed.
onStop()
5
This callback is called when the activity is no longer visible.
onDestroy()
6
This callback is called before the activity is destroyed by the system.
onRestart()
7
This callback is called when the activity restarts after stopping it.
Android runs on a variety of devices that offer different screen sizes and densities. For
applications, the Android system provides a consistent development environment across
devices and handles most of the work to adjust each application's user interface to the
screen on which it is displayed. At the same time, the system provides APIs that allow
you to control your application's UI for specific screen sizes and densities, in order to
optimize your UI design for different screen configurations. For example, you might want
a UI for tablets that's different from the UI for handsets.
Although the system performs scaling and resizing to make your application work on
different screens, you should make the effort to optimize your application for different
screen sizes and densities. In doing so, you maximize the user experience for all devices
and your users believe that your application was actually designed for their devices—
rather than simply stretched to fit the screen on their devices.
By following the practices described in this document, you can create an application that
displays properly and provides an optimized user experience on all supported screen
configurations, using a single .apk file.
This section provides an overview of Android's support for multiple screens, including:
an introduction to the terms and concepts used in this document and in the API, a
summary of the screen configurations that the system supports, and an overview of the
API and underlying screen-compatibility features.
Screen size
Actual physical size, measured as the screen's diagonal.
For simplicity, Android groups all actual screen sizes into four generalized sizes:
small, normal, large, and extra-large.
Screen density
The quantity of pixels within a physical area of the screen; usually referred to as
dpi (dots per inch). For example, a "low" density screen has fewer pixels within a
given physical area, compared to a "normal" or "high" density screen.
For simplicity, Android groups all actual screen densities into six generalized
densities: low, medium, high, extra-high, extra-extra-high, and extra-extra-extra-
high.
Orientation
The orientation of the screen from the user's point of view. This is either
landscape or portrait, meaning that the screen's aspect ratio is either wide or tall,
respectively. Be aware that not only do different devices operate in different
orientations by default, but the orientation can change at runtime when the user
rotates the device.
Resolution
The total number of physical pixels on a screen. When adding support for
multiple screens, applications do not work directly with resolution; applications
should be concerned only with screen size and density, as specified by the
generalized size and density groups.
Density-independent pixel (dp)
A virtual pixel unit that you should use when defining UI layout, to express layout
dimensions or position in a density-independent way.
Android provides support for multiple screen sizes and densities, reflecting the many
different screen configurations that a device may have. You can use features of the
Android system to optimize your application's user interface for each screen
configuration and ensure that your application not only renders properly, but provides the
best user experience possible on each screen.
To simplify the way that you design your user interfaces for multiple screens, Android
divides the range of actual screen sizes and densities into:
Note: Beginning with Android 3.2 (API level 13), these size groups are
deprecated in favor of a new technique for managing screen sizes based on the
available screen width. If you're developing for Android 3.2 and greater, see
Declaring Tablet Layouts for Android 3.2 for more information.
Each generalized size and density spans a range of actual screen sizes and densities. For
example, two devices that both report a screen size of normal might have actual screen
sizes and aspect ratios that are slightly different when measured by hand. Similarly, two
devices that report a screen density of hdpi might have real pixel densities that are
slightly different. Android makes these differences abstract to applications, so you can
provide UI designed for the generalized sizes and densities and let the system handle any
final adjustments as necessary. Figure 1 illustrates how different sizes and densities are
roughly categorized into the different size and density groups.
Figure 1. Illustration of how Android roughly maps actual sizes and densities to
generalized sizes and densities (figures are not exact).
As you design your UI for different screen sizes, you'll discover that each design requires
a minimum amount of space. So, each generalized screen size above has an associated
minimum resolution that's defined by the system. These minimum sizes are in "dp"
units—the same units you should use when defining your layouts—which allows the
system to avoid worrying about changes in screen density.
Note: These minimum screen sizes were not as well defined prior to Android 3.0, so you
may encounter some devices that are mis-classified between normal and large. These are
also based on the physical resolution of the screen, so may vary across devices—for
example a 1024x720 tablet with a system bar actually has a bit less space available to the
application due to it being used by the system bar.
To optimize your application's UI for the different screen sizes and densities, you can
provide alternative resources for any of the generalized sizes and densities. Typically,
you should provide alternative layouts for some of the different screen sizes and
alternative bitmap images for different screen densities. At runtime, the system uses the
appropriate resources for your application, based on the generalized size or density of the
current device screen.
You do not need to provide alternative resources for every combination of screen size and
density. The system provides robust compatibility features that can handle most of the
work of rendering your application on any device screen, provided that you've
implemented your UI using techniques that allow it to gracefully resize (as described in
the Best Practices, below).
Density independence
Your application achieves "density independence" when it preserves the physical size
(from the user's point of view) of user interface elements when displayed on screens with
different densities.
Example application without support for different densities, as shown on low, medium,
and high-density screens.
Example application with good support for different densities (it's density independent),
as shown on low, medium, and high density screens.
The Android system helps your application achieve density independence in two ways:
The system scales dp units as appropriate for the current screen density
The system scales drawable resources to the appropriate size, based on the current
screen density, if necessary
In most cases, you can ensure density independence in your application simply by
specifying all layout dimension values in density-independent pixels (dp units) or with
"wrap_content", as appropriate. The system then scales bitmap drawables as appropriate
in order to display at the appropriate size, based on the appropriate scaling factor for the
current screen's density.
However, bitmap scaling can result in blurry or pixelated bitmaps, which you might
notice in the above screenshots. To avoid these artifacts, you should provide alternative
bitmap resources for different densities. For example, you should provide higher-
resolution bitmaps for high-density screens and the system will use those instead of
resizing the bitmap designed for medium-density screens.
Intents
An Android Intent is an abstract description of an operation to be performed. It
can be used with startActivity to launch an Activity, broadcastIntent to send it to any
interested BroadcastReceiver components, and startService(Intent) or
bindService(Intent, ServiceConnection, int) to communicate with a background
Service.
For example, let's assume that you have an Activity that needs to launch an email
client and sends an email using your Android device. For this purpose, your Activity
would send an ACTION_SEND along with appropriate chooser, to the Android Intent
Resolver. The specified chooser gives the proper interface for the user to pick how to
send your email data.
Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email, "Choose an email client from..."));
Above syntax is calling startActivity method to start an email activity and result should
be as shown below −
There are separate mechanisms for delivering intents to each type of component −
activities, services, and broadcast receivers.
Sr.No Method & Description
Context.startActivity()
1
The Intent object is passed to this method to launch a new activity or get an
existing activity to do something new.
Context.startService()
2
The Intent object is passed to this method to initiate a service or deliver new
instructions to an ongoing service.
Context.sendBroadcast()
3
The Intent object is passed to this method to deliver the message to all interested
broadcast receivers.
Intent Objects
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.
Action
This is mandatory part of the Intent object and is a string naming the action to be
performed — or, in the case of broadcast intents, the action that took place and is being
reported. The action largely determines how the rest of the intent object is structured .
The Intent class defines a number of action constants corresponding to different intents.
Here is a list of Android Intent Standard Actions
The action in an Intent object can be set by the setAction() method and read by
getAction().
Data
Adds a data specification to an intent filter. The specification can be just a data type (the
mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by
separate attributes for each of its parts −
These attributes that specify the URL format are optional, but also mutually dependent −
If a scheme is not specified for the intent filter, all the other URI attributes are
ignored.
If a host is not specified for the filter, the port attribute and all the path attributes
are ignored.
The setData() method specifies data only as a URI, setType() specifies it only as a MIME
type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read
by getData() and the type by getType().
There are given a lot of android widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar
etc.
Android widgets are easy to learn. The widely used android widgets with examples are
given below:
Android Button
Android Toast
Custom Toast
We are able to customize the toast, such as we can display image on the toast
ToggleButton
CheckBox
AlertDialog
AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.
Spinner
Spinner displays the multiple options, but only one can be selected at a time.
AutoCompleteTextView
RatingBar
DatePicker
Datepicker displays the datepicker dialog that can be used to pick the date.
TimePicker
TimePicker displays the timepicker dialog that can be used to pick the time.
ProgressBar
Button control
A Button is a Push-button which can be pressed, or clicked, by the user to perform an
action.
Button Attributes
Following are the important attributes related to Button control. You can check Android
official documentation for complete list of attributes and related methods which you can
use to change these attributes are run time.
Here, we are going to create two textfields and one button for sum of two numbers. If
user clicks button, sum of two input values is displayed on the Toast.
First of all, drag 2 textfields from the Text Fields palette and one button from the Form
Widgets palette as shown in the following figure.
File: activity_main.xml
Layouts
We have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either
at run time using View/ViewGroup objects or you can declare your layout using simple
XML file main_layout.xml which is located in the res/layout folder of your project.
A layout may contain any type of widgets such as buttons, labels, textboxes, and
so on. Following is a simple example of XML file having LinearLayout
There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.
Grid View
7
GridView is a ViewGroup that displays items in a two-dimensional, scrollable
grid.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There
are few common attributes among all the layouts and their are other attributes which are
specific to that layout. Following are common attributes and will be applied to all the
layouts:
Toggle button
Toggle Button
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the
button.
It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides slider
control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.
Method Description
Returns the text when button is not in the checked
CharSequence getTextOff()
state.
CharSequence getTextOn() Returns the text for when button is in the checked
state.
void setChecked(boolean
Changes the checked state of this button.
checked)
Android Spinner is like the combox box of AWT or Swing. It can be used to display the
multiple options to the user in which only one item can be selected by the user.
Android spinner is like the drop down menu with multiple values from which the end
user can select only one value.
Android spinner is associated with AdapterView. So you need to use one of the adapter
classes with spinner.
In this example, we are going to display the country list. You need to use ArrayAdapter
class to store the country list.
activity_main.xml
Drag the Spinner from the pallete, now the activity_main.xml file will like this:
Images
Android provides many views which we can use to define a user interface for our
apps. Amongst these it provides a large number to display information and take input
from the user, these include text and image views.
Android provides views which can be used to display images from various
sources and provide transitions between them. Some of these views are the ImageView
and the ImageSwitcher. These views provide a high level of functionality to display
images in a user interface so that we can concentrate on the images we want to display
rather than taking care of rendering.
Nested classes
Image.Plane
class
A single color plane of image data.
Public methods
close()
abstract
void
Free up this frame for reuse.
getCropRect()
Rect
Get the crop rectangle associated with this frame.
getFormat()
abstract
int
Get the format for this image.
getHeight()
abstract
int
The height of the image in pixels.
getPlanes()
abstract
Plane[]
Get the array of pixel planes for this Image.
getTimestamp()
abstract
long
Get the timestamp associated with this frame.
getWidth()
abstract
int
The width of the image in pixels.
setCropRect(Rect cropRect)
void
Set the crop rectangle associated with this frame.
setTimestamp(long timestamp)
void
Set the timestamp associated with this frame.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
addImagesToThegallery();
}
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.
Android Option Menus are the primary menus of android. They can be used for
settings, search, delete item etc.
Here, we are going to see two examples of option menus. First, the simple option menus
and second, options menus with images.
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.
Let's see how to create menu in android. Let's see the simple option menu example that
contains three menu items.
activity_main.xml
File: activity_main.xml
Dialog
A Dialog is small window that prompts the user to 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.
In order to make an alert dialog, you need to make an object of AlertDialogBuilder which
an inner class of AlertDialog. Its syntax is given below
Now you have to set the positive (yes) or negative (no) button using the object of the
AlertDialogBuilder class. Its syntax is
alertDialogBuilder.setPositiveButton(CharSequence text,
DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text,
DialogInterface.OnClickListener listener)
Apart from this , you can use other functions provided by the builder class to customize
the alert dialog. These are listed below
Application context
It is an instance which can be accessed in an activity via getApplicationContext().
This context is tied to the lifecycle of an application. The application context can be used
where you need a context whose lifecycle is separate from the current context or when
you are passing a context beyond the scope of an activity.
We generally call context when we need to get information about different parts of our
application like Activities, Applications etc.
getContext()
getBaseContext()
getApplicationContext()
this
Need of Context :
The documentation says that every view needs the context to access the right
resources (e.g. the theme, strings etc.).
1.Because the resources must be accessible while the view is being constructed
(the constructor will need some resources to fully initialise the view).
2.This allows the flexibility of using a context that is different from the one of the
current activity (imagine a view that uses some other string resources and not the
ones from the current activity).
3.The designers of the Android SDK seem to have chosen that the context must
be set only once and then stay the same throughout the lifetime of the view.
PART-B
Two mark Questions
PART-C
EIGHT MARK QUESTIONS
1.Explain Application context with suitable program.
2.Discuss the user interface design of Android.
3.Discuss TextField in Android with suitable example.
4.Discuss Layouts and Button control of Android.
5.Explain Activity Life cycle in User Interface Architecture
6.Discuss in detail (i) Form Widgets (ii) Images
7.Discuss the user interface architecture of Android.
8.Explain Menu and Dialog controls of Android.
9.Explain the user interface design of Android.
10.Discuss Application context and intents of Android user interface architecture.
Which of the following can Progress Progress Progress Both Both a&b
you use to display a progress Bar Dialog View a&b
bar in an Android application?
Which of the following is/are Activity. Activity. Activity. Activity. Activity.on
appropriate for saving the state onFreeze( onPause( onStop() onDestro Pause()
of an Android application? ) ) y()
Unit-5 Notes
Syllabus:
Database: Understanding of SQL database - connecting with the database.
SQLite Database
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.
There are other functions available in the Cursor class that allows us to effectively
retrieve the data. That includes
column
getColumnName(int columnIndex)
3
This method returns the name of the column by specifying the index of the column
getColumnNames()
4
This method returns the array of all the column names of the table.
getCount()
5
This method returns the total number of rows in the cursor
getPosition()
6
This method returns the current position of the cursor in the table
isClosed()
7
This method returns true if the cursor is closed and return false otherwise
For managing all the operations related to the database , an helper class has been given
and is called SQLiteOpenHelper. It automatically manages the creation and update of the
database. Its syntax is given below
File: Contact.java
MYSQL is used as a database at the webserver and PHP is used to fetch data from
the database. Our application will communicate with the PHP page with necessary
parameters and PHP will contact MYSQL database and will fetch the result and return
the results to us.
PHP - MYSQL
Creating Database
MYSQL database can be created easily using this simple script. The CREATE
DATABASE statement creates the database.
<?php
$con=mysqli_connect("example.com","username","password");
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
}
?>
Creating Tables
Once database is created, its time to create some tables in the database. The CREATE
TABLE statement creates the database.
<?php
$con=mysqli_connect("example.com","username","password","my_db");
$sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role
CHAR(30))";
if (mysqli_query($con,$sql)) {
echo "Table have been created successfully";
}
?>
When the database and tables are created. Now its time to insert some data into the tables.
The Insert Into statement creates the database.
<?php
$con=mysqli_connect("example.com","username","password","my_db");
$sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin',
'admin','adminstrator')";
if (mysqli_query($con,$sql)) {
There are two ways to connect to MYSQL via PHP page. The first one is called Get
method. We will use HttpGet and HttpClient class to connect. Their syntax is given
below −
After that you need to call execute method of HttpClient class and receive it in a
HttpResponse object. After that you need to open streams to receive the data.
In the Post method, the URLEncoder,URLConnection class will be used. The urlencoder
will encode the information of the passing variables. It's syntax is given below −
The last thing you need to do is to write this data to the link. After writing, you need to
open stream to receive the responded data.
PART-B
Two mark Questions
PART-C
EIGHT MARK QUESTIONS
The android OS comes with All of Location Sensor WiFi? All of these
many useful system services, these and Readings Hot and more
which include processes you more Spots
can easily ask for things such
as your..
Which of the following is the Closing Suspendi Opening Restorin Opening a
most “resource hungry” part of an app ng an app a new g the new app
dealing with Activities on app most
Android? recent
app
Android Applications must be After Before Never Within Before they
signed they are they are two are
installed installed weeks of installed
installati
on
Which of the following would import import import import import
you have to include in your android.c android. android.d android.d android.wi
project to use the ontent widget atabase atabase.s dget
SimpleAdapter class? qlite
What operating system is used Linux Windows Java XML Linux
as the base of the Android
stack?
What runs in the background Intents Content Services Applicati Services
and doesn’t have any UI Providers ons
components?
Although most people’s first Oracle Dalvik
Open The Open
thought when they think of Technolo Handset above Handset
Android is Google, Android is gy Alliance statement Alliance
not actually owned by Google. is and
Who owns the Android Android
platform? is owned
by
Google
Broadcast receivers are Observer Mediator Comman Facade Observer
Android’s implementation of a d
system-wide publish/subscribe
mechanism, or more precisely,
what design pattern?
What does the Gargenta mean He means He means He means Not He means
in his Design Philosophy when that when that the that we known that we will
he says that the project will, we finish program will work work on the
“Always be whole and the entire must on the program by
complete”? project always be program adding self-
we will able to by adding contained
have a compile self- chunks to it
working contained so ,Each
applicatio chunks to additional
n, even it so chunk
though ,Each simply adds
there will additiona a new
be points l chunk functionalit
along the simply y to the
way adds a application
when we new
will stop functiona
and the lity to the
applicatio applicatio
n will not n
run
The android OS comes with All of Location Sensor WiFi? All of these
many useful system services, these and Readings Hot and more
which include processes you more Spots
can easily ask for things such
as your..
What year was development on 2003 2005 2007 2006 2005
the Dalvik virtual machine
started?
What is an Activity? A single message A Context A single
screen sent compone referring screen the
the user among nt that to the user sees
sees on the major runs in applicati on the
the building the on device at
device at blocks backgrou environm one time
one time nd ent
without
any
interface
Android releases since 1.5 Adjective Food Somethin America Food
have been given nicknames and g that n states
derived how? strange starts w/
animal ‘A’ ->
Somethin
g that
starts w/
‘B’…
Which of the following are not Resource All of Native Dalvik All of these
a component of an APK file? s these are Libraries executabl are
compone e component
nts of the s of the
APK APK
Why the so few users are left The first 1.0 and 1.0 and Everyone Everyone
with versions 1.0 and 1.1? phones 1.1 had 1.1 are with 1.0 with 1.0
were security just and 1.1 and 1.1
released holes that number were were
with forced designati upgraded upgraded to
version carriers ons for to 1.5 1.5 over the
1.5 to recall the over the air
phones version air automatical
using Apple’s automati ly
them iPhone is cally
running
Android Applications must be After Before Never Within Before they
signed they are they are two are
installed installed weeks of installed
installati
on
What built-in database is SQLite MySQL Apache Oracle SQLite
Android shipped with?
What year was development on 2003 2005 2007 2006 2005
the Dalvik virtual machine
started?
What is an Activity? A single message A Context A single
screen sent compone referring screen the
the user among nt that to the user sees
sees on the major runs in applicati on the
the building the on device at
device at blocks backgrou environm one time
one time nd ent
without
any
interface
As an Android programmer, Versions Versions Versions Versions Versions
what version of Android 1.6 or 2.0 1.0 or 1.1 1.2 or 1.3 2.3 or 3.0 1.6 or 2.0
should you use as your
minimum development target?
How does Google check for Every Users Google A Users
malicious software in the new app report employee separate report
Android Market? is malicious s verify company malicious
scanned software each new monitors software to
by a virus to Google app the Google
scanner Android
Market
for
Google
What does the .apk extension Applicati Applicati Android Android Application
stand for? on on Proprieta Package Package
Package Program ry Kit
Kit
Scanned by CamScanner
Reg No. …….…………..
[ 17CAU304A ]
Karpagam Academy Of Higher Education
(Established Under Section 3 of UGC Act 1956)
COIMBATORE – 641 021
SECTION – B (3 X 2 =6 Marks)
ANSWER ALL THE QUESTIONS
[OR]
(b) Explain the Android operating System.
Android is a mobile operating system developed by Google, based on the Linux kernel and designed
primarily for touchscreen mobile devices such as smartphones and tablets. Android's user interface is
mainly based on direct manipulation, using touch gestures that loosely correspond to real-world
actions, such as swiping, tapping and pinching, to manipulate on-screen objects, along with a virtual
keyboard for text input. In addition to touchscreen devices, Google has further developed Android
TV for televisions, Android Auto for cars, and Android Wear for wrist watches, each with a
specialized user interface. Variants of Android are also used on notebooks,game consoles, digital
cameras, and other electronics.
Initially developed by Android Inc., which Google bought in 2005, Android was unveiled in 2007,
along with the founding of the Open Handset Alliance – a consortium of hardware, software, and
telecommunication companies devoted to advancing open standardsfor mobile devices.
Beginning with the first commercial Android device in September 2008, the operating system has
gone through multiple major releases, with the current version being 7.0 "Nougat", released in August
2016. Android applications ("apps") can be downloaded from the Google Play store, which features
over 2.7 million apps as of February 2017. Android has been the best-selling OS on tablets since 2013,
and runs on the vast majority[a] of smartphones. As of May 2017, Android has two billion monthly
active users, and it has the largest installed base of any operating system.
25. (a) Explain Android Development Tools .
Android software development is the process by which new applications are created for the Android
operating system. Applications are usually developed inJava programming language using the
Android software development kit (SDK), but other development environments are also available.
The Android software development kit (SDK) includes a comprehensive set of development
tools.[4] These include a debugger, libraries, a handset emulatorbased on QEMU, documentation,
sample code, and tutorials. Currently supported development platforms include computers
running Linux (any modern desktop Linux distribution), Mac OS X 10.5.8 or later, and Windows 7or
later. As of March 2015, the SDK is not available on Android itself, but software development is
possible by using specialized Android applications.
Until around the end of 2014, the officially supported integrated development environment (IDE)
was Eclipse using the Android Development Tools (ADT) Plugin, though IntelliJ IDEA IDE (all
editions) fully supports Android development out of the box,[8] and NetBeans IDE also supports
Android development via a plugin.[9] As of 2015, Android Studio,[10] made by Google and powered by
IntelliJ, is the official IDE; however, developers are free to use others, but Google made it clear that
ADT was officially deprecated since the end of 2015 to focus on Android Studio as the official
Android IDE.[11] Additionally, developers may use any text editor to edit Java and XML files, then
use command line tools (Java Development Kit and Apache Ant are required) to create, build and
debug Android applications as well as control attached Android devices (e.g., triggering a reboot,
installing software package(s) remotely).
[OR]
(b) Explain the architecture of Android.
Android is an open source, Linux-based software stack created for a wide array of devices and form
factors. The following diagram shows the major components of the Android platform.
The foundation of the Android platform is the Linux kernel. For example, the Android Runtime
(ART) relies on the Linux kernel for underlying functionalities such as threading and low-level
memory management.
Using a Linux kernel allows Android to take advantage of key security features and allows device
manufacturers to develop hardware drivers for a well-known kernel.
The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware
capabilities to the higher-level Java API framework. The HAL consists of multiple library modules,
each of which implements an interface for a specific type of hardware component, such as
the camera or bluetooth module. When a framework API makes a call to access device hardware, the
Android system loads the library module for that hardware component.
Android Runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process
and with its own instance of the Android Runtime (ART). ART is written to run multiple virtual
machines on low-memory devices by executing DEX files, a bytecode format designed specially for
Android that's optimized for minimal memory footprint. Build toolchains, such as Jack, compile Java
sources into DEX bytecode, which can run on the Android platform.
[OR]
(b) Explain the concept of polymorphism in Java.
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method overriding.
Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading
2) Method Overriding
Method Overloading:
In Java, it is possible to define two or more methods of same name in a class, provided that there
argument list or parameters are different. This concept is known as Method Overloading.
Example:
class Overload{
void demo (int a) {
System.out.println ("a: " + a); }
void demo (int a, int b) {
System.out.println ("a and b: " + a + "," + b); }
double demo(double a) {
System.out.println("double a: " + a);
return a*a; }}
class MethodOverloading{
public static void main (String args []) {
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Register Number____________
[17CAU304A]
SECTION – B (3 X 2 =6 Marks)
ANSWER ALL THE QUESTIONS
The Java virtual machine is an abstract (virtual) computer defined by a specification. This
specification omits implementation details that are not essential to ensure interoperability: the memory
layout of run-time data areas, the garbage-collection algorithm used, and any internal optimization of
the Java virtual machine instructions (their translation into machine code). The main reason for this
omission is to not unnecessarily constrain implementers. Any Java application can be run only inside
some concrete implementation of the abstract specification of the Java virtual machine.[1]
Starting with Java Platform, Standard Edition (J2SE) 5.0, changes to the JVM specification have been
developed under the Java Community Process as JSR 924. As of 2006, changes to specification to
support changes proposed to the class file format (JSR 202) are being done as a maintenance release of
JSR 924. The specification for the JVM was published as the blue book, The preface states:
We intend that this specification should sufficiently document the Java Virtual Machine to make
possible compatible clean-room implementations. Oracle provides tests that verify the proper
operation of implementations of the Java Virtual Machine.
One of Oracle's JVMs is named HotSpot, the other, inherited from BEA Systems is JRockit. Clean-
room Java implementations include Kaffe and IBM J9. Oracle owns the Java trademark and may allow
its use to certify implementation suites as fully compatible with Oracle's specification.
[OR]
(b) Explain about JVM languages.
A JVM language is any language with functionality that can be expressed in terms of a valid
class file which can be hosted by the Java Virtual Machine. A class file contains Java Virtual
Machine instructions (Java byte code) and a symbol table, as well as other ancillary
information. The class file format is the hardware- and operating system-independent binary
format used to represent compiled classes and interfaces.
There are several JVM languages, both old languages ported to JVM and completely new
languages. JRuby and Jython are perhaps the most well-known ports of existing languages, i.e.
Ruby and Python respectively. Of the new languages that have been created from scratch to
compile to Java bytecode, Clojure, Groovy and Scala may be the most popular ones. A notable
feature with the JVM languages is that they are compatible with each other, so that, for
example, Scala libraries can be used with Java programs and vice versa.
Java 7 JVM implements JSR 292: Supporting Dynamically Typed Languages on the Java
Platform, a new feature which supports dynamically typed languages in the JVM. This feature
is developed within the Da Vinci Machine project whose mission is to extend the JVM so that
it supports languages other than Java
[OR]
(b) Explain the virtual machine for Android sandwich.
Android is Linux based open source operating system, especially designed for touch based smart
phones and tablets and is one of the most widely used operating system by Mobile phone and tablets
manufacturers. As Android OS only supports ARM architecture based hardware so you can't run it on
x86 architecture i.e. Computer or laptop. In order to run it on x86 architecture, you need to have an
Android OS which supports x86 architecture luckily Android x86 project provides it for various
testing purposes and you can install Android OS along with your Windows Vista, 7 & 8 operating
system.
Steps for installing Android OS Ice Cream Sandwich on Virtual PC
As I am using Microsoft Windows 8 OS thus I have mentioned the steps for installing Android OS on
Virtual PC along with Windows 8(learn how to install Windows 8 on virtual PC) but these steps are
very much applicable to Windows Vista and 7.
- Now visit android-x86.org site and head over to download page. If your system name is listed then
download the Android OS ISO image from the respective link else download the ISO image especially
created for x86 architecture based hardware which will work on every system (from here
https://docs.google.com/open?id=0B4GbJReHMmu_amMzQzJoNGw3WFU). Also if you experience
internet connectivity and audio problem with ISO image downloaded for respective system then
download the generic ISO image from link given above
- Now open Oracle VM VirtualBox and press CTRL + N for creating a new Virtual Machine and also
click the Hide Description button to make visible the hidden Hard drive options