Sie sind auf Seite 1von 42

Day 1 at Corporate Computers

Following topics are covered by


Kumari Bindu R

 History of Python
 Features of Python
 Class & Objects
 Class Inheritance
 Python List
 Python Tuples
 Python Sets
 Python Dictionaries
 Python classes & Objects
 Python Database Connectivity
 Python in GUI- tkinter
Introduction to Python

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

 Web development (server-side),


 Software development, mathematics,
 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.
 System scripting.
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-orientated way or a functional way.
Features Of Python
1. Easy to code:
Python is high level programming language. Python is very easy to learn language as compared to other
language like c, c#, java script, java etc. It is very easy to code in python language and anybody can learn
python basic in few hours or days. It is also developer-friendly language.

2. Free and Open Source:


Python language is freely available at official website and you can download it from the given download
link below click on the Download Python keyword. Since, it is open-source; this means that source code
is also available to the public. So you can download it as, use it as well as share it.

3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object oriented
language and concepts of classes, objects encapsulation etc.

4. GUI Programming Support:


Graphical Users interfaces can be made using a module such as PyQt5, PyQt4, wxPython or Tk in
python.PyQt5 is the most popular option for creating graphical apps with Python.

5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the
system architecture, nor do we need to manage the memory.

6. Extensible feature:
Python is a Extensible language. We can write our some python code into c or c++ language and also we
can compile that code in c/c++ language.

7. Python is Portable language:


Python language is also a portable language. For example, if we have python code for windows and if we
want to run this code on other platform such as Linux, Unix and Mac then we do not need to change it, we
can run this code on any platform.

8. Python is Integrated language:


Python is also an Integrated language because we can easily integrated python with other language like c,
c++ etc.

9. Interpreted Language:
Python is an Interpreted Language, because python code is executed line by line at a time. Like other
language c, c++, java etc there is no need to compile python code this makes it easier to debug our code.
The source code of python is converted into an immediate form called bytecode.

10. Large Standard Library


Python has a large standard library which provides rich set of module and functions so you do not have to
write your own code for every single thing, there are many libraries present in python for such as regular
expressions, unit-testing, web browsers etc.

11. Dynamically Typed Language:


Python is dynamically-typed language. That means the type (for example, int, double, long etc) for a
variable is decided at run time not in advance, because of this feature we don’t need to specify the type of
variable.
Classes & Objects

 Class − A user-defined prototype for an object that defines a set of attributes that characterize any
object of the class. The attributes are data members (class variables and instance variables) and
methods, accessed via dot notation.
 Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for
example, is an instance of the class Circle.
 Instantiation − The creation of an instance of a class.

 Method − A special kind of function that is defined in a class definition.


 Object − A unique instance of a data structure that's defined by its class. An object comprises both
data members (class variables and instance variables) and methods.

An Example of covering all these concepts together


class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Class Inheritance
Create a class by deriving it from a preexisting class by listing the parent class in parentheses after the
new class name.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were
defined in the child class. A child class can also override data members and methods from the parent.
Derived classes are declared much like their parent class; however, a list of base classes to inherit from
is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite

An example

class Parent: # define parent class


parentAttr = 100
def __init__(self):
print "Calling parent constructor"

def parentMethod(self):
print 'Calling parent method'

def setAttr(self, attr):


Parent.parentAttr = attr

def getAttr(self):
print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class


def __init__(self):
print "Calling child constructor"

def childMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
Python Lists
A list is a collection which is ordered and changeable. It allows duplicate members. In Python lists are
written with square brackets.

Eg: thislist= [“apple”,”banana”,”cherry”]


Print(thislist)

Python Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.

thislist= (“apple”,”banana”,”cherry”)]
Print(thislist)

Python Sets
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.

thislist= {“apple”,”banana”,”cherry”}
Print(thislist)

Python Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.

Thisdist= {

“brand”: “ford”,
“model”: “mustang”,
“year”: 1964
}
Print(Thisdist)
Python Modules
A module is a file consisting of Python code. A module can define functions, classes and variables. A module
can also include runnable code.
def print_func( par ):
print "Hello : ", par
return

Python Database Connectivity

There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Python Example to connect MySQL Database

To connect the MySQL database, you must know the database name you want to connect. Run below
query on MySQL console if you have not created any database in MySQL. Otherwise, you can skip the
below query.

Create Database in MySQL


Create database Electronics;

Below is the last step, i.e. using methods of MySQL Connector Python to connect MySQL database. Let
see the example now.
import mysql.connector
from mysql.connector import Error

try:
connection = mysql.connector.connect(host='localhost',
database='Electronics',
user='pynative',
password='pynative@#29')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)

except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")

After connecting to MySQL Server, The output is


Connected to MySQL Server version 5.7.19
You're connected to database: ('electronics',)
MySQL connection is closed

MySQL is the Database used for Database Connection.

Python GUI –tkinter


Python offers multiple options for developing GUI (Graphical User Interface). tkinter is most commonly
used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with
tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is
an easy task.

To create a tkinter:

1. Importing the module – tkinter


2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

Importing tkinter is same as importing any other module in the python c

from tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()

The output is

Day 2 &Day3 at Corporate Computers


Following topics are covered by
Rajendrakumar R Nair

 Introduction to Java
 Features of Java
 Oops Concepts
 Class
 Object
 Methods
 Inheritance
 Abstraction
 Polymorphism
 Encapsulation
 Constructors
 Exception Handling
 This Keyword
 Multithreading
 Applet
 JDBC(Java Database Connectivity)

Introduction to Java

Java is a programming language originally developed by James Gosling at Sun Microsystems (which is
now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun
Microsystems' Java platform.

Java is a high-level object-oriented programming language developed by Sun Microsystems.It was only
developed keeping in mind the consumer electronics and communication equipments. It came into
existence as a part of web application, web services and a platform independent programming language in
1990s.

Earlier, C++ was widely used to write object oriented programming languages , however,it was not a
platform independent and needed to be recompiled for each different CPUs. A team of Sun Microsystems
in the guidance of James Goslings decided to develop an advanced programming language for the
betterment of consumer electronic devices. In the year 1991 they make a platform independent software
and named it Oak. But later due to some patent conflicts , it was renamed as Java and in 1995 the Java 1.0
was officially released to the world.

It promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms.

Features Of Java

1. Simple
We wanted to build a system that could be programmed easily without a lot of esoteric
training and which leveraged today’s standard practice. So even though we found that C++ was
unsuitable, we designed Java as closely to C++ as possible in order to make the system more
comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ that, in our
experience, bring more grief than benefit.

2. Object Oriented
Simply stated, object-oriented design is a technique for programming that focuses on the data (= objects)
and on the interfaces to that object. To make an analogy with carpentry, an “object-oriented” carpenter
would be mostly concerned with the chair he was building, and secondarily with the tools used to make it;
a “non-objectoriented”carpenter would think primarily of his tools. The object-oriented facilities of Java
are essentially those of C++.

3. Robust
Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of
emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating
situations that are error-prone. . . . The single biggest difference between Java and C/C++ is that Java has
a pointer model that eliminatesthe possibility of overwriting memory and corrupting data.

4. Secure
Java is intended to be used in networked/distributed environments. Toward that end, a lot of emphasis has
been placed on security. Java enables the construction of virus-free, tamper-free systems.

5. Portable
Unlike C and C++, there are no “implementation-dependent” aspects of the specification. The sizes of the
primitive data types are specified, as is the behavior of arithmetic on them.

6. Interpreted
The Java interpreter can execute Java bytecodes directly on any machine to which the interpreter has been
ported. Since linking is a more incremental and lightweight process, the development process can be
much more rapid and exploratory.

7. High Performance
While the performance of interpreted bytecodes is usually more than adequate, there are situations where
higher performance is required. The bytecodes can be translated on the fly (at runtime) into machine code
for the particular CPU the application is running on.

8. Multithreaded
[The] benefits of multithreading are better interactive responsiveness and real-time behavior.

9. Dynamic
In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an
evolving environment. Libraries can freely add new methods and instance variables without any effect on
their clients. In Java, finding out runtime type information is straightforward.

Oops Concepts
1.Classes

A class is the template or blueprint from which objects are made. Thinking about classes as cookie
cutters. Objects are the cookies themselves. When you construct an object from a class, you are said to
have created an instance of the class.

General form of a class :


A class is declared by use of the class keyword. The classes can get much more complex.The general
form of a class definition is shown as

class class_name
{
type instance-variable1;
type instance-variable2;

type method-name(parameter-list){
//body of method
}
}

2.Objects
 Objects are the basic run time entity or in other words object is a instance of a class . An object is
a software bundle of variables and related methods of the special class.
 Each object made from a class can have its values for the instance variables of that class.

Syntax for the Object :


class_name object_name = new class_name();

To work with OOP, you should be able to identify three key characteristics of objects:
• The object’s behavior—What can you do with this object, or what methods can you apply to it?
• The object’s state—How does the object react when you apply those methods?
• The object’s identity—How is the object distinguished from others that may have the same behavior and
state?

3. Methods

A class has one or more methods .Methods must be de clared inside the class.Within the curly braces of a
method, write the instructions for how that method should be performed. Method code is basically a set of
statements , and you can think of a method kind of like a function or procedure.

public class class_name


{
returntype method_name()
{
//statements;
}
}

4.Inheritance

 When one class inherits from another , it is called Inheritance.


 The class which is inherited is called superclass and the class which inherits is called
subclass.
 So we can say that subclass extends superclass but subclass can add new methods and instance
variables of its own and it can override the methods of superclass.
Example :
Interface

 Interfaces are similar to classes but they lack instance variables and their methods are declared
without any body.
 Any number of classes can implement an interface, also one class can implement any number of
interfaces.

 So , by implementing many interfaces in a same class , we can use the concept of multiple
inheritance.

 All the methods in an interface are public.

To make a class implement an interface , we carry out 2 steps:

1.Declare that class intends to implement the given interface.

2.Supply definition for all methods in the interface.

Defining an Interface:

access modifier interface name{

returntype method1(parameter list);

returntype method2(parameter list);

Implementing an interface:

access modifier class classname implements interface{

returntype method1(){

//body

returntype method2(){

// body

5.Abstraction

The process of abstraction in Java is used to hide certain details and only show the essential features of
the object. Through the process of abstraction, a programmer hides all but the relevant data about
an object in order to reduce complexity and increase efficiency. In the same way that abstraction
sometimes works in art, the object that remains is a representation of the original, with unwanted
detail omitted. The resulting object itself can be referred to as an abstraction, meaning a named
entity made up of selected attributes and behavior specific to a particular usage of the originating
entity.

 An abstract class has no use , no value , no purpose in life unless it is extended.


 An abstract class means that nobody can ever make a new instance of that class.

Syntax:

abstract public class canine extends Animal


{
Public void roam()
{
}
}

6.Polymorphism

 It describes the ability of the object in belonging to different types with specific behavior of each
type.
 It can be done by two ways:

 Overloading
 Overriding
Overloading

 An overloaded method is just a different method that happens to have the same method name.
 An overloaded method is NOT the same as an overridden method.
 The returntype can be different.
 The number of parameters can be different.
 Datatype of parameters can also be different.

Example

public class overloads{


String uniqueID;
public int addNums(int a,int b){
return a+b;
}
public double addNums(double a , double b){
return a+b;
}
}
Overriding

 An instance method in a subclass with the same signature and returntypes as an instance method
in the superclass overrides the siperclass’s method.
 The overriding method has same name , numer and types of parameters and return types as the
method it overrides.
 If a subclass defines a method with same signature as a class method in the superclass , the
method in subclass hides the one in superclass.

public class Animal {


public static void testClassMethod() {
System.out.println(“The class method in Animal”);
}
public void testInstanceMethod() {
System.out.println(“The instance method in Animal”);
}
}

Public class Cat extends Animal{


Public static void testClassMethod(){
System.out.println(“The Class Method in Cat”);
}
Public void testInstanceMethod(){
System.out.println(“The Instance method in Cat.”);
}

Public static void main(String args[]){


Cat mycat= new Cat();
Animal myanimal= mycat();
Animal.testClassMethod();
Myanimal.testInsatnceMethod();
}
}

The cat class overrides the instance method in Animal.

The Output from this program is as follows:

The class method in Animal.


The instance method in Cat.

7.Encapsulation
Encapsulation is the concept of hiding the implementation details of a class and allowing access to the
class through a public interface. For this, we need to declare the instance variables of the class as private
or protected.

The client code should access only the public methods rather than accessing the data directly. Also, the
methods should follow the Java Bean's naming convention of set and get.

Encapsulation makes it easy to maintain and modify code. The client code is not affected when the
internal implementation of the code changes as long as the public method signatures are unchanged. For
instance:

public class Employee


{
private float salary;
public float getSalary()
{
return salary;
}
public void setSalary(float salary)
{
this.salary = salary;
}
Constructor
A class contains constructors that are invoked to create objects from the class blueprint. Constructor
declarations look like method declarations—except that they use the name of the class and have no return
type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {


gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Exception Handling
 An exception arises in code at runtime.
 Exception are a clean way to manage abnormal states.
 Exception : mild error which you can handle.
 Error: serious error cause termination.
 An Exception is thrown and then caught.

Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs
that occurs during the program execution. During the program execution if any error occurs and you want
to print your own message or the system message about the error then you write the part of the program
which generate the error in the try{} block and catch the errors using catch() block. Exception turns the
direction of normal flow of the program control and send to the related catch() block. Error that occurs
during the program execution generate a specific object which has the information about the errors
occurred in the program.
How to handle Exceptions?
This keyword
 When we declare the name of instance variable and local variables same , This keyword helps us
to avoid name conflicts.
 In the example, this.length and this.breadth refers to the instance variable length and breadth
while length and breadth refers to the arguments passed in the method

Example

class Rectangle{
int length,breadth;
void show(int length,int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}

Output:

C:\java>java UseOfThisOperator
The area of a Rectangle is : 30
Multithreading

 Multithreaded programs extend the idea of multitasking.


 Individual programs will appear to do multiple tasks at the same time . Each task is called a
thread.
 Programs that can run more than one thread at once are said to be multithreaded.
 Process speed can be increased by using threads because the thread can stop or suspend a specific
running process and start or resume the suspended processes.

Example:

public class Threads{


public static void main(String[] args){
Thread th = new Thread();
System.out.println("Numbers are printing line by line after 5 seconds : ");
try{
for(int i = 1;i <= 10;i++)
{
System.out.println(i);
th.sleep(5000);
}
}
catch(InterruptedException e){
System.out.println("Thread interrupted!");
e.printStackTrace();
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Applet
 A Java applet is an applet delivered to the users in the form of Java bytecode. Java applets can
run in a Web browser using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand-
alone tool for testing applets. Java applets were introduced in the first version of the Java
language in 1995.
 Applets are also used to create onlinegame collections that allow players to compete against live
opponents in real-time.

A Java applet can have any or all of the following advantages:

 It is simple to make it work on Linux, Windows and Mac OS i.e. to make it cross platform.
Applets are supported by most web browsers
 Applets also improve with use: after a first applet is run, the JVM is already running and starts
quickly (JVM will need to restart each time the browser starts fresh).
 It can move the work from the server to the client, making a web solution more scalable with the
number of users/clients
 The applet naturally supports the changing user state like figure positions on the chessboard.

Example:
Java Database Connectivity
JDBC is Java application programming interface that allows the Java programmers to access database
management system from Java code. It was developed byJavaSoft, a subsidiary of Sun Microsystems.
In short JDBC helps the programmers to write java applications that manage these three programming
activities:

1. It helps us to connect to a data source, like a database.


2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.

How to use JDBC?

1. Load the JDBC driver. To load a driver, you specify the classname of the database driver in the
Class.forName method. By doing so, you automatically create a driver instance and register it with the
JDBC driver manager.

2. Define the connection URL. In JDBC, a connection URL specifies the server host, port, and database
name with which to establish a connection.

3. Establish the connection. With the connection URL, username, and password, a network connection
to the database can be established. Once the connection is established, database queries can be performed
until the connection is closed.

4. Create a Statement object. Creating a Statement object enables you to send queries and commands to
the database.

5. Execute a query or update. Given a Statement object, you can send SQL statements to the database
by using the execute, executeQuery, executeUpdate, or executeBatch methods.

6. Process the results. When a database query is executed, a ResultSet is returned. The ResultSet
represents a set of rows and columns that you can process by calls to next and various getXxx methods.

7. Close the connection. When you are finished performing queries and processing results, you should
close the connection, releasing resources to the database.

MySQL Database is used to practice connection.


Day 4 at Corporate Computers
Following topics are covered

 Introduction to PHP
 Features of PHP
 Oops Concepts
 PHP syntax
 Database
 PHP Forms and User Input
Introduction to PHP
PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way
back in 1994.
 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
 PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
 It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
 PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on
the Unix side. The MySQL server, once started, executes even very complex queries with
huge result sets in record-setting time.
 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4
added support for Java and distributed object architectures (COM and CORBA), making n-
tier development a possibility for the first time.
 PHP is forgiving: PHP language tries to be as forgiving as possible.
 PHP Syntax is C-Like.

Common uses of PHP


 PHP performs system functions, i.e. from files on a system it can create, open, read, write,
and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, through email you can
send data, return data to the user.
 You add, delete, modify elements within your database through PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.

Characteristics of PHP
Five important characteristics make PHP's practical nature possible −

 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

Features Of PHP
 Simple

 Faster

 Interpreted

 Open Source

 Case Sensitive

 Simplicity

 Efficiency

 Platform Independent

 Security

 Flexibility

 Familiarity

 Error Reporting

 Loosely Typed Language

 Real-Time Access Monitoring

Oops Concepts
OOPs Concepts in PHP
PHP is an object oriented scripting language; it supports all of the above principles. The
above principles are achieved via;

 Encapsulation - via the use of “get” and “set” methods etc.


 Inheritance - via the use of extends keyword
 Polymorphism - via the use of implements keyword

Now that we have the basic knowledge of OOP and how it is supported in PHP, let us look
at examples that implement the above principles

PHP syntax:
<?php echo "Hello, World!";?>

Database
phpMyAdmin supports MySQL-compatible databases.

• MySQL 5.5 or newer

• MariaDB 5.5 or newer

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms

PHP Forms and User Input


The PHP $_GET and $_POST variables are used to retrieve information from forms, like user
input.
The $_GET Function

The built-in $_GET function is used to collect values from a form sent with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in the
browser's address bar) and has limits on the amount of information to send (max. 100 characters).

The $_POST Function

The built-in $_POST function is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of
information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the
post_max_size in the php.ini file).

Form design For Employee Record Management system

Login form

Profile page
Edit Educational details
Android
Android is an operating systems. That is, it’s software that connects hardware to software and
provides general services. But more than that, it’s a mobile specific operating system: an OS
designed to work on mobile (read: handheld, wearable, carry-able) devices.

Note that the term “Android” also is used to refer to the “platform” (e.g., devices that use the
OS) as well as the ecosystem that surrounds it. This includes the device manufacturers who use
the platform, and the applications that can be built and run on this platform. So “Android
Development” technically means developing applications that run on the specific OS, it also
gets generalized to refer to developing any kind of software that interacts with the platform.

Android Versions
Android has gone through a large number of “versions” since it’s release:

Date Version Nickname API Level

Sep 2008 1.0 Android 1

Apr 2009 1.5 Cupcake 3

Sep 2009 1.6 Donut 4

Oct 2009 2.0 Eclair 5

May 2010 2.2 Froyo 8

Dec 2010 2.3 Gingerbread 9

Feb 2011 3.0 Honeycomb 11

Oct 2011 4.0 Ice Cream Sandwich 14

July 2012 4.1 Jelly Bean 16

Oct 2013 4.4 KitKat 19

Nov 2014 5.0 Lollipop 21


Date Version Nickname API Level

Oct 2015 6.0 Marshmallow 23

Aug 2016 7.0 Nougat 24

Mar 2017 O preview Android O Developer Preview

Each different “version” is nicknamed after a dessert, in alphabetica order. But as developers,
what we care about is the API Level, which indicates what different
programming interfaces (classes and methods) are available to use.

Additionally, Android is an “open source” project released through the “Android Open Source
Project”, or ASOP. You can find the latest version of the operating system code
at https://source.android.com/; it is very worthwhile to actually dig around in the source code
sometimes!

While new versions are released fairly often, this doesn’t mean that all or even many devices
update to the latest version. Instead, users get updated phones historically by purchasing new
devices (every 18m on average in US). Beyond that, updates—including security updates—have
to come through the mobile carriers, meaning that most devices are never updated beyond the
version that they are purchases with.

This is a problem from a consumer perspective, particularly in terms of security! There are some
efforts on Google’s part to to work around this limitation by moving more and more platform
services out of the base operating system into a separate “App” called Google Play Services.

But what this means for developers is that you can’t expect devices to be running the latest
version of the operating system—the range of versions you need to support is much greater than
even web development!

Android Architecture and Code


Developing Android applications involves interfacing with the Android platform and framework.
Thus you need a high level understanding of the architecture of the Android platform.
Like so many other systems, the Android platform is built as a layered architecture:

o At it’s base, Android runs on a Linux kernel for interacting with the device’s processor,
memory, etc. Thus an Android device can be seen as a Linux computer.
o On top of that kernel is the Hardware Abstraction Layer: an interface to drivers that can
programmatically access hardware elements, such as the camera, disk storage, Wifi
antenna, etc.
 These drivers are generally written in C; we won’t interact with them directly in
this course.
o On top of the HAL is the Runtime and Android Framework, which provides a set of
abstraction in the Java language which we all know an love. For this course, Android
Development will involve writing Java applications that interact with the Android
Framework layer, which handles the task of interacting with the device hardware for us.

Programming Languages
There are two programming languages we will be working with in this course:
1. Java: Android code (program control and logic, as well as data storage and manipulation) is
written in Java.

Writing Android code will feel a lot writing any other Java program: you create classes, define
methods, instantiate objects, and call methods on those objects. But because you’re working
within a framework, there is a set of code that already exists to call specific methods. As a
developer, your task will be to fill in what these methods do in order to run your specific
application.

o In web terms, this is closer to working with Angular (a framework) than jQuery (a
library).
o Importantly: this course expects you to have “journeyman”-level skills in Java
(apprenticeship done, not yet master). We’ll be using a number of intermediate concepts
(like generics and inheritance) without much fanfare or explanation .

2. XML: Android user interfaces and resources are specified


in XML (EXtensible Markup Language). To compare to web programming: the XML contains
what would normally go in the HTML/CSS, while the Java code will contain what would
normally go in the JavaScript.

XML is just like HTML, but you get to make up your own tags. Except we’ll be using the ones
that Android made up; so it’s like defining web pages, except with a new set of elements. This
course expects you to have some familiarity with HTML or XML, but if not you should be able
to infer what you need from the examples.

Building Apps
Pre-Lollipop (5.0), Android code ran on Dalvik: a virtual machine similar to the JVM used by
Java SE.

Fun fact for people with a Computer Science background: Dalvik uses a register-based
architecture rather than a stack-based one!

A developer would write Java code, which would then be compiled into JVM bytecode, which
would then be translated into DVM (Dalvik virtual machine) bytecode, that could be run on
Android devices. This DVM bytecode was stored in .dex or .odex (“[Optimized] Dalvik
Executable”) files, which is what was loaded onto the device. The process of converting from
Jave code to dex files is called “dexing” (so code that has been built is “dexed”).

Dalvik does include JIT (“Just In Time”) compilation to native code that runs much faster than
the code interpreted by the virtual machine, similar to the Java HotSpot. This navite code is
faster because no translation step is needed to talk to the actual hardware (the OS).
From Lollipop (5.0) on, Android instead uses Android Runtime (ART) to run code. ART’s
biggest benefit is that it compiles the .dex bytecode into native code on installation using AOT
(“Ahead of Time”) compilation. ART continues to accept .dex bytecode for backwards
compatibility (so the same dexing process occurs), but the code that is actually installed and run
on a device is native. This allows for applications to have faster execution, but at the cost of
longer install times—but since you only install an application once, this is a pretty good trade.

After being built, Android applications (the source, dexed bytecode, and any resources) are
packaged into .apk files. These are basically zip files (they use the same gzip compression); if
you rename the file to be .zip and you can unpackage them! The .apk files are
then cryptographically signed to specify their authenticity, and either “side-loaded” onto the
device or uploaded to an App Store for deployment.

o The signed .apk files are basically the “executable” versions of your program!
o Note that the Android application framework code is actually “pre-DEXed” (pre-
compiled) on the device; when you write code, you’re actually compiling against empty
code stubs (rather than needing to include those classes in your .apk)! That said, any
other 3rd-party libraries you include will be copied into your built App, which can
increase its file size both for installation and on the device.

To summarize, in addition to writing Java and XML code, when building an App you need to:

1. Generate Java source files (e.g., from resource files, which are written XML used to
generate Java code)
2. Compile Java code into JVM bytecode
3. “dex” the JVM bytecode into Dalvik bytecode
4. Pack in assets and graphics into an APK
5. Cryptographically sign the APK file to verify it
6. Load it onto the device

There are a lot of steps here, but there are tools that take care of it for us. We’ll just write Java
and XML code and run a “build” script to do all of the steps!

Development Tools
There are a number of different hardware and software tools you will need to do Android
development:

1.3.1 Hardware

Since Android code is written for a virtual machine anyway, Android apps can be developed and
built on any computer’s operating system (unlike some other mobile OS…).
But obviously Android apps will need to be run on Android devices. Physical devices are the
best for development (they are the fastest, easiest way to test), though you’ll need USB cable to
be able to wire your device into your computer. Any device will work for this course; you don’t
even need cellular service (just WiFi should work). Note that if you are unfamiliar with Android
devices, you should be sure to play around with the interface to get used to the interaction
language, e.g., how to click/swipe/drag/long-click elements to use an app.

You will need to turn on developer options in order to install development apps on your device!

If you don’t have a physical device, it is also possible to use the Android Emulator, which is a
“virtual” Android device. The emulator represents a generic device with hardware you can
specify… but it does have some limitations (e.g., no cellular service, no bluetooth, etc).

While it has improved recently, the Emulator historically does not work very well on Windows; I
recommend you develop on either a Mac or a physical device. In either case, make sure you have
enabled HAXM (Intel’s Acceleration Manager, which allows the emulator to utilize your GPU
for rendering): this speeds things up considerably.

Software
Software needed to develop Android applications includes:

 The Java 7 SDK (not just the JRE!) This is because you’re writing Java code!
 Gradle or Apache ANT. These are automated build tools—in effect, they let you specify
a single command that will do a bunch of steps at once (e.g., compile files, dex files,
move files, etc). These are how we make the “build script” that does the 6 build steps
listed above.
o ANT is the “old” build system, Gradle is the “modern” build system (and so what
we will be focusing on).
o Note that you do not need to install Gradle separately for this course.
 Android Studio & Android SDK is the official IDE for developing Android applications.
Note that the IDE comes bundled with the SDK. Android Studio provides the main build
system: all of the other software (Java, Gradle) goes to support this.
The SDK comes with a number of useful command-line tools. These include:
o adb, the “Android Device Bridge”, which is a connection between your computer
and the device (physical or virtual). This tool is used for console output!
o emulator, which is a tool used to run the Android emulator
o deprecated/removed android: a tool that does SDK/AVD (Android Virtual
Device) management. Basically, this command-line utility did everything that the
IDE did, but from the command-line! It has recently been removed from the IDE.
I recommend making sure that the SDK command-line tools are installed. Put
the tools and platform-tools folders on your computer’s PATH; you can run adb to check
that everything works. All of these tools are built into the IDE, but they can be useful
fallbacks for debugging.

Hello World
As a final introductory steps, this lecture will walk you through creating and running a basic App
so that you can see what you will actually be working with. You will need to have Android
Studio installed for this to work.

1. Launch Android Studio if you have it (may take a few minutes to open)
2. Start a new project.
o Use your UW NetID in the domain.
o Make a mental note of the project location so you can find your code later!
o Target: this is the “minimum” SDK you support. We’re going to target Ice Cream
Sandwich (4.0.3, API 15) for most this class, as the earliest version of Android
most our apps will support.
 Note that this is different than the “target SDK”, which is the version of
Android you tested your application against (e.g., what system did you run
it on?) For this course we will be testing on API 21 (Lollipop); we’ll
specify that in a moment.
3. Select an Empty Activity
o Activities are “Screens” in your application (things the user can do). Activities are
discussed in more detail in the next lecture.
4. And boom, you have an Android app! Aren’t frameworks lovely?

The Emulator
We can run our app by clicking the “Play” or “Run” button at the top of the IDE. But we’ll need
a device to run the app on, so let’s make an emulator!

The Nexus 5 is a good choice for supporting “older” devices. The new Pixel is also a reasonable
device to test against.

o You’ll want to make sure you create a Lollipop device, using the Google APIs (so we
have special classes available to us), and amost certainly running on x86 (Intel) hardware
o Make sure that you’ve specified that it accepts keyboard input. You can always edit this
emulator later (Tools > Android > AVD Manager).

After the emulator boots, you can slide to unlock, and there is our app!
Project Contents
Note that Android Studio by default shows the “Android” view, which organizes files
thematically. If you go to the “Project” view you can see what the actual file system looks like.
In Android view, files are organized as follows:

 app/ folder contains our application


o manifests/ contains the Android Manifest files, which is sort of like a “config” file
for the app
o java/ contains the Java source code for your project. You can find
the MyActivity file in here
o res/ contains resource files used in the app. These are where we’re going to put
layout/appearance information
 Also have the Gradle scripts. There are a lot of these:
o build.gradle: Top-level Gradle build; project-level (for building!)
o app/build.gradle: Gradle build specific to the app use this one to customize
project!. We can change the Target SDK in here!
o proguard-rules.pro: config for release version (minimization, obfuscation, etc).
o gradle.properties: Gradle-specific build settings, shared
o local.properties: settings local to this machine only
o settings.gradle: Gradle-specific build settings, shared

Note that ANT would instead give:

o build.xml: Ant build script integrated with Android SDK


o build.properties: settings used for build across all machines
o local.properties: settings local to this machine only

We’re using Gradle, but it is good to be aware of ANT stuff for legacy purposes

 res has resource files. These are XML files that specify details of the app–such as layout.
o res/drawable/: contains graphics (PNG, JPEG, etc)
o res/layout/: contains UI XML layout files
o res/mipmap/: conatins launcher icon files in different resolutions
 Fun fact: MIP stands for “multum in parvo”, which is Latin for “much in
little” (because multiple resolutions of the images are stored in a single
file). “Map” is used because Mipmaps are normally used for texture
mapping.
o res/values/: contains XML definitions for general constants

We can also consider what the application code does. While we’ll revisit this in more detail in
the next lecture, it’s useful to start seeing how the framework is structured:
We’ll start with the MyActivity Java source file. This class extends Activity (actually it extends a
subclass that supports Material Design components), allowing us making our own
customizations to what the app does.

In this class, we override the onCreate() method that is called by the framework when the
Activity starts (see next lecture).

 We call the super method, and then setContentView() to specify what the content
(appearance) of our Activity is. This is passed in a value from something called R. R is a
class that is generated at compile time and contains constants that are defined by the
XML “resource” files! Those files are converted into Java variables, which we can access
through the R class.

R.layout refers to the “layout” XML resource, so can go there (remember: inside res/). Opening
these XML files they appear in a “design” view. This view lets you use a graphical system to lay
out your application (similar to a PowerPoint slide).

 However, even as the design view becomes more powerful, using it is still frowned upon
by many developers for historical reasons. It’s often cleaner to write out the layouts and
content in code. This is the same difference between writing your own HTML and using
something like FrontPage or DreamWeaver or Wix to create a page. While those are
legitimate applications, they are less “professional”.

In the code view, we can see the XML: tags, attributes, values. Tags nested inside one another.
The provided XML code defines a layout, and inside that is a TextView (a View representing
some text), which has a value: text! We can change that and then re-run the app to see it update!

 It’s also possible to define this value in values/strings (e.g., as a constant), then refer to
as @string/message. More on this proces later.

Finally, as a fun demonstration, try to set an icon for the App (in Android Studio, go to: File >
New > Image Asset

Das könnte Ihnen auch gefallen