Beruflich Dokumente
Kultur Dokumente
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:
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.
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.
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.
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.
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
An example
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
def childMethod(self):
print 'Calling child method'
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
There are the following steps to connect a python application to our 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.
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")
To create a tkinter:
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
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.
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.
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.
4.Inheritance
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.
Defining an Interface:
Implementing an 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.
Syntax:
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
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.
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:
To create a new Bicycle object called myBike, a constructor is called by the new operator:
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
Example:
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.
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. 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.
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.
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
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;
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.
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
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 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).
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:
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!
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 .
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:
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